用Windows API取得窗體句柄二例
發(fā)表時(shí)間:2023-08-01 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]文/胡克 Windows通過句柄(Handle)識(shí)別每個(gè)窗體、控件、菜單和菜單項(xiàng),當(dāng)程序運(yùn)行時(shí),它所包含的每個(gè)部件都有一個(gè)惟一確定的句柄同其他的部件相區(qū)別句柄在Windows API中具有舉足輕重...
文/胡克
Windows通過句柄(Handle)識(shí)別每個(gè)窗體、控件、菜單和菜單項(xiàng),當(dāng)程序運(yùn)行時(shí),它所包含的每個(gè)部件都有一個(gè)惟一確定的句柄同其他的部件相區(qū)別句柄在Windows API中具有舉足輕重的作用,現(xiàn)舉三例,有興趣的讀者不妨一試。
獲取窗體和控件的句柄
步驟如下:
1、為了看到顯示于屏幕上所有的窗體和控件的句柄,用SetWindowPos函數(shù)設(shè)置窗口始終在最上面,其他窗口不能覆蓋它,并使其只以標(biāo)題顯示于屏幕左上角。
(1)新建一工程,打開API Viwer:Add-ins→API Viewer→File→Load text file→Win32api.txt。
(2)將SetWindowPos函數(shù)的聲明粘貼到窗體的聲明部分:Private Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long。
(3)程序啟動(dòng)時(shí)調(diào)用SetWindowPos函數(shù),窗體Load事件代碼如下:
Private Sub Form_Load()
SetWindowPos Me.hwnd, -1, 0, 0, 0, 0, conSwpNoActivate Or conSwpShowWindow'使窗體一直置于最頂層
End Sub
臥龍傳說提醒:當(dāng)?shù)诙䝼(gè)參數(shù)hWndInsertAfter的值為-1時(shí)置于頂層;值為-2時(shí)不置于頂層。
2、為了找到鼠標(biāo)指針的X和Y坐標(biāo),用上面同樣的方法,通過API Viewer工具把獲取的鼠標(biāo)指針位置的API函數(shù)GetCursorPos的聲明和結(jié)構(gòu)類型聲明粘貼到窗體的聲明部分:
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Type POINTAPI
x As Long
y As Long
3、用API Viewer把指定點(diǎn)的窗口的句柄的API函數(shù)WindowFromPointXY的聲明粘貼到窗體的聲明部分:
Private Declare Function WindowFromPointXY Lib "user32" Alias
"WindowFromPoint" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
4、在窗體上添加timer控件,并把Interval屬性設(shè)為500(毫秒),用如下的Timer事件完成操作:
Private Sub Timer1_Timer()
Dim xy As POINTAPI'(聲明變量類型)
GetCursorPos xy'(取得XY的座標(biāo))
ahwnd = WindowFromPointXY(xy.x, xy.y) '(取得當(dāng)前鼠標(biāo)坐標(biāo)下窗口的句柄)
Me.Caption = ahwnd'(在標(biāo)題欄顯示當(dāng)前坐標(biāo)下窗口的句柄)
End Sub
獲取激活窗口的句柄
用GetFocus函數(shù)可獲得激活窗口(擁有輸入焦點(diǎn)的窗口)的句柄。
1、用API Viewer工具將函數(shù)GetFocus的聲明粘貼到窗體的聲明部分:
Private Declare Function GetFocus Lib "user32" Alias "GetFocus" () As Long
2、新建一工程,添加兩個(gè)文本框text1和text2,兩個(gè)文本框控件的GotFocus事件代碼如下:
Sub Text1_GotFocus()
h&& = GetFocus&&()
Debug.Print h&&(在立即窗口顯示當(dāng)前窗口句柄)
End Sub
Private Sub Text2_GotFocus()
h&& = GetFocus&&()
Debug.Print h&
End Sub