有用的GetForegroundWindow

 

這個小例子就是用來演示如何得到Windows桌面上處於活動狀態的窗口的句柄的。

使用一個Timer控件就可以搞定。在本例中再通過GetWindowText函數來處理得到句柄後的操作。

1。新建一個標準VB6的EXE工程,加入Timer控件
2。API函數的聲明

private Declare Function GetForegroundWindow Lib "user32" () as Long
private Declare Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (byval hwnd as Long, _
       byval lpString as string, byval cch as Long) as Long

3。在窗體的Load事件中加入代碼:

Private Sub Form_Load()
    Timer1.Interval = 100 '設置間隔時間
End Sub

4。在Timer控件中的Timer事件中加入代碼:

Private Sub Timer1_Timer()
    Static CurrentHwnd As Long
    Dim ForegroundWindowHwnd As Long
    Dim sText As String * 255
    ForegroundWindowHwnd = GetForegroundWindow
    If ForegroundWindowHwnd = CurrentHwnd Then Exit Sub
    CurrentHwnd = ForegroundWindowHwnd
    If CurrentHwnd <> hwnd Then
        Caption = "ActiveWidow's Caption: " & Left$(sText, GetWindowText(CurrentHwnd, sText, 255))
    Else
        Caption = "ActiveWindow's Caption: Form1"
    End If
End Sub

本程序在Win2000 + Vb6 中調試通過

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章