思路,用windows API函数 GetForegroundWindow 得到前台窗口的句柄,然后跟窗口的句柄比较... 如果相同就是得到焦点,否则失去焦点,例子中我用的timer检测,,,,,,代码如下 Option ExplicitPrivate Declare Function GetForegroundWindow Lib "user32" () As Long
Private Sub Form_Load()
Timer1.Interval = 10
End SubPrivate Sub Timer1_Timer()
Dim thwnd As Long
thwnd = GetForegroundWindow
If thwnd <> Me.hWnd Then
Me.Caption = "失去焦点"
Else
Me.Caption = "得到焦点"
End If
End Sub
'第一种:这下只能在多窗口程序中有效:Private Sub Form_Deactivate()
MsgBox "失去焦点了"
End Sub '第二种:要用API:'添加一个定时器,interval设为1000Private Declare Function GetActiveWindow Lib "user32" () As Long
Dim H As Long
Private Sub Timer1_Timer()
H = GetActiveWindow
If H <> Me.hWnd Then
MsgBox "失去焦点"
End If
End Sub
简单点的方法是:
在窗体上放一个Timer,将Interval设为100。然后输入以下代码:
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Sub Timer1_Timer()
If GetForegroundWindow() <> hWnd Then StartSecurity
End Sub