获取活动窗口的标题

时间:2013-02-21 10:32:29

标签: vb.net winforms winapi dllimport user32

我已声明以下WinAPI调用

<DllImport("USER32.DLL", EntryPoint:="GetActiveWindow", SetLastError:=True,
    CharSet:=CharSet.Unicode, ExactSpelling:=True,
    CallingConvention:=CallingConvention.StdCall)>
Public Shared Function GetActiveWindowHandle() As System.IntPtr
End Function

<DllImport("USER32.DLL", EntryPoint:="GetWindowText", SetLastError:=True,
    CharSet:=CharSet.Unicode, ExactSpelling:=True,
    CallingConvention:=CallingConvention.StdCall)>
Public Shared Function GetActiveWindowText(ByVal hWnd As System.IntPtr, _
                                            ByVal lpString As System.Text.StringBuilder, _
                                            ByVal cch As Integer) As Integer
End Function

然后,我调用此子例程来获取活动窗口标题栏中的文本

Public Sub Test()
    Dim caption As New System.Text.StringBuilder(256)
    Dim hWnd As IntPtr = GetActiveWindowHandle()
    GetActiveWindowText(hWnd, caption, caption.Capacity)
    MsgBox(caption.ToString)
End Sub

最后,我收到以下错误

  

无法在DLL中找到名为“GetWindowText”的入口点   'USER32.DLL'

如何解决此问题?

1 个答案:

答案 0 :(得分:7)

<DllImport("USER32.DLL", EntryPoint:="GetWindowText", SetLastError:=True,
    CharSet:=CharSet.Unicode, ExactSpelling:=True,

你坚持使用ExactSpelling。问题是,user32.dll导出的两个版本的GetWindowText。 GetWindowTextA和GetWindowTextW。 A版本使用ansi字符串,这是在Windows ME中最后使用的默认代码页中编码的具有8位字符的旧字符串格式。 W版本使用Unicode字符串,以utf-16编码,即本机Windows字符串类型。 pinvoke marshaller将根据CharSet尝试其中任何一个,但是你通过使用ExactSpelling:= True来阻止它。所以它找不到GetWindowText,它不存在。

使用EntryPoint:=“GetWindowTextW”或删除ExactSpelling。