vb.net 获取活动窗口的标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14999997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:27:13  来源:igfitidea点击:

Get the title of the active window

vb.netwinformswinapidllimportuser32

提问by Max

I have declared the following WinAPI calls

我已经声明了以下 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

Then, I call this subroutine to get the text in the active window's title bar

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

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

Finally, I get the following error

最后,我收到以下错误

Unable to find an entry point named 'GetWindowText' in DLL 'USER32.DLL'

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

How can I fix this issue?

我该如何解决这个问题?

回答by Hans Passant

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

You insisted on ExactSpelling. Which is the problem, there are twoversions of GetWindowText exported by user32.dll. GetWindowTextA and GetWindowTextW. The A version uses an ansi string, a legacy string format with 8-bit characters encoded in the default code page that was last used in Windows ME. The W version uses a Unicode string, encoded in utf-16, the native Windows string type. The pinvoke marshaller will try either of them, based on the CharSet but you stopped it from doing so by using ExactSpelling := True. So it cannot find GetWindowText, it doesn't exist.

您坚持使用 ExactSpelling。这是哪个问题,user32.dll导出的GetWindowText有两个版本。GetWindowTextA 和 GetWindowTextW。A 版本使用 ansi 字符串,这是一种旧的字符串格式,其 8 位字符编码在 Windows ME 上次使用的默认代码页中。W 版本使用 Unicode 字符串,以 utf-16 编码,Windows 原生字符串类型。pinvoke 编组器将根据 CharSet 尝试其中的任何一个,但您使用 ExactSpelling := True 阻止了它这样做。所以它找不到GetWindowText,它不存在。

Either use EntryPoint := "GetWindowTextW" or drop ExactSpelling.

使用 EntryPoint := "GetWindowTextW" 或删除 ExactSpelling。