获取活动窗口的标题

Max*_*Max 2 vb.net winapi user32 dllimport winforms

我已经声明了以下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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

最后,我收到以下错误

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

我该如何解决这个问题?

Han*_*ant 7

<DllImport("USER32.DLL", EntryPoint:="GetWindowText", SetLastError:=True,
    CharSet:=CharSet.Unicode, ExactSpelling:=True,
Run Code Online (Sandbox Code Playgroud)

你坚持使用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.