VB.NET调用GetWindowTextA及GetWindowRect

这2个函数在windows开发人员中心的说明见:GetWindowTextAGetWindowRect

对windows api的调用,关键就是要正确声明相关api的函数,我原来就是因为注释中的错误,导致调用出错,在VB.NET中声明这2个函数:

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Integer, ByVal lpString As StringBuilder, ByVal cch As Int32) As Integer 
'如果参数lpString声明为string,不能获取正确窗口标题

Declare Auto Function GetWindowRect Lib "USER32.DLL" (ByVal hWnd As IntPtr, ByRef lpRect As RECT) As Boolean 
'参数lpRect为指针,所以使用ByRef

其实在微软开发人员中心中关于GetWindowTextA的示例代码也可以看到,lpString不能简单的声明为string类型数据:

HWND hwndCombo; 
int cTxtLen; 
PSTR pszMem; 
 
......
 
                // Allocate memory for the string and copy 为字符串分配内存并复制 
                // the string into the memory. 将字符串放入内存中。
 
                pszMem = (PSTR) VirtualAlloc((LPVOID) NULL, 
                    (DWORD) (cTxtLen + 1), MEM_COMMIT, 
                    PAGE_READWRITE); 
                GetWindowText(hwndCombo, pszMem, 
                    cTxtLen + 1); 

这可能涉及到该文中说的:图析:String,StringBuffer与StringBuilder的区别

微软开发人员中心中关于GetWindowRect的示例代码也可以看到,参数lpRect 使用了传址符&,在VB.NET则是定义为ByRef 

HWND hwndOwner; 
RECT rc, rcDlg, rcOwner; 

....
 
    GetWindowRect(hwndOwner, &rcOwner); 
    GetWindowRect(hwndDlg, &rcDlg); 
    CopyRect(&rc, &rcOwner); 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VB.NET 获取所有窗口句柄可以使用 Windows API 函数 EnumWindows 和 GetWindowText、GetClassName。 EnumWindows 函数用于枚举所有顶层窗口,示例代码如下: ``` Private Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As EnumWindowsCallback, ByVal lParam As IntPtr) As Boolean Private Delegate Function EnumWindowsCallback(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean Private Function EnumWindowsProc(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean ' 处理枚举到的窗口句柄 Return True ' 返回 True 继续枚举,返回 False 停止枚举 End Function EnumWindows(AddressOf EnumWindowsProc, IntPtr.Zero) ``` GetWindowText 函数用于获取窗口标题,示例代码如下: ``` Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As IntPtr, ByVal lpString As StringBuilder, ByVal nMaxCount As Integer) As Integer Dim title As StringBuilder = New StringBuilder(256) GetWindowText(hWnd, title, 256) ``` GetClassName 函数用于获取窗口类名,示例代码如下: ``` Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As IntPtr, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer Dim className As StringBuilder = New StringBuilder(256) GetClassName(hWnd, className, 256) ``` 注意:在使用 EnumWindows 函数枚举窗口时,需要在回调函数处理枚举到的窗口句柄,可以通过 GetWindowText 和 GetClassName 函数获取窗口标题和类名。同时,需要注意窗口标题和类名可能包含文字符,需要使用 StringBuilder 对象来存储。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值