当用户从excel更改为另一个程序时,我有一个我想要关闭的用户表单。 我曾尝试在ThisWorkbook中使用工作表停用事件,但它没有做到这一点。
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Unload UserForm1
End Sub
答案 0 :(得分:2)
这样的事情
Declare PtrSafe Function GetForegroundWindow Lib "user32.dll" () As LongPtr
Declare PtrSafe Function GetActiveWindow Lib "user32.dll" () As LongPtr
Sub test()
Dim wbHwnd As LongPtr
Dim fHwnd As LongPtr
Dim aHwnd As LongPtr
'replace with timer class that ticks
Application.OnTime Now + TimeValue("00:00:10"), "test", , True
wbHwnd = Application.hWnd
fHwnd = GetForegroundWindow
aHwnd = GetActiveWindow
If wbHwnd <> fHwnd Then
Debug.Print "Lost focus"
Else
Debug.Print "Has focus"
End If
End Sub
这只是获取当前应用程序的Hwnd并将其与前台窗口进行比较。而不是使用Application.Ontime,最好使用以设定的间隔打勾的计时器类。
此外,您可以更具体,并将Hwnd用于userform而不是Application。如果您保留Ontime事件,请记住在工作簿关闭或类似的情况下停用计时器。
编辑:
假设Userform具有唯一标题,您可以使用USerform标题找到HWnd
Declare PtrSafe Function GetForegroundWindow Lib "User32.dll" () As LongPtr
Declare PtrSafe Function GetActiveWindow Lib "User32.dll" () As LongPtr
Private Declare PtrSafe Function FindWindow Lib "User32.dll" Alias "FindWindowA" _
(ByVal ClassName As String, ByVal WindowName As String) As LongPtr
Sub test()
Dim wbHwnd As LongPtr
Dim fHwnd As LongPtr
Dim aHwnd As LongPtr
Dim ufHwnd As LongPtr
'replace with timer class that ticks
Application.OnTime Now + TimeValue("00:00:10"), "test", , True
wbHwnd = Application.hWnd
fHwnd = GetForegroundWindow
aHwnd = GetActiveWindow
ufHwnd = FindWindow("ThunderDFrame", UserForm1.Caption)
If wbHwnd <> fHwnd Then
Debug.Print "Lost focus " & wbHwnd & " " & fHwnd & " " & aHwnd & " " & ufHwnd
Else
Debug.Print "Has focus " & wbHwnd & " " & fHwnd & " " & aHwnd & " " & ufHwnd
End If
End Sub