Class中不可以调用,因为根本就没有DC.其实TextWidth这个函数可能是根据API GetTextExtentPoint32或DrawText返回的,它们都需要hDC. 可行的办法是创建一个MemoryDC,CreateFontIndirect创建Font,用GetTextExtentPoint32去获取。例如: Public Function TextWidth(ByVal sText As String) As LongDim sz As SizeAPI On Error Resume Next '--- state check If Not IsMemoryDCCreated() Then Exit Function End If
可行的办法是创建一个MemoryDC,CreateFontIndirect创建Font,用GetTextExtentPoint32去获取。例如:
Public Function TextWidth(ByVal sText As String) As LongDim sz As SizeAPI On Error Resume Next
'--- state check
If Not IsMemoryDCCreated() Then
Exit Function
End If
GetTextExtentPoint32 m_hMemoryDC, sText, Len(sText), sz
'--- success
TextWidth = sz.cxEnd Function