怎的设置窗体为活动窗口并且可以接受按键消息
怎样设置窗体为活动窗口并且可以接受按键消息?
搜集了这么一堆api函数,发现怎么整都不管用。
我的测试代码:
测试方法:
启动程序后立刻随便点击一个程序作为活动窗口,然后看看上面代码在3秒到了后能不能正确设置自己为活动窗口并且接受SendKeys发送的字符串。
------解决方案--------------------
Private Declare Function SetFocusAPI Lib "user32" Alias "SetFocus" (ByVal hwnd As Long) As Long此函数声明有误。
测试通过啊……
------解决方案--------------------
发现从某些全屏窗体切换过来,sendkey发送不成功,考虑是代码执行速度太快所致,修改下代码,让它有100ms的延时,测试通过。
搜集了这么一堆api函数,发现怎么整都不管用。
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function SetActiveWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SetFocusAPI Lib "user32" Alias "SetFocus" (ByVal hwnd As Long)
我的测试代码:
'添加一个text1、一个timer1设置延时为3秒
Option Explicit
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function SetActiveWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SetFocusAPI Lib "user32" Alias "SetFocus" (ByVal hwnd As Long)
Private Const WM_SYSCOMMAND = &H112
Private Const SC_RESTORE = &HF120&
Private Sub Timer1_Timer()
SendMessage Me.hwnd, WM_SYSCOMMAND, SC_RESTORE, Me.hwnd
SetForegroundWindow Me.hwnd
SetActiveWindow Me.hwnd
SetFocusAPI Me.hwnd
Text1.SetFocus
SendKeys "123"
End Sub
测试方法:
启动程序后立刻随便点击一个程序作为活动窗口,然后看看上面代码在3秒到了后能不能正确设置自己为活动窗口并且接受SendKeys发送的字符串。
------解决方案--------------------
'添加一个text1、一个timer1设置延时为3秒
Option Explicit
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function SetActiveWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Const WM_SYSCOMMAND = &H112
Private Const SC_RESTORE = &HF120&
Private Sub Timer1_Timer()
SendMessage Me.hwnd, WM_SYSCOMMAND, SC_RESTORE, Me.hwnd
SetForegroundWindow Me.hwnd
SetActiveWindow Me.hwnd
SetFocusAPI Me.hwnd
Text1.SetFocus
SendKeys "123"
End Sub
Private Declare Function SetFocusAPI Lib "user32" Alias "SetFocus" (ByVal hwnd As Long) As Long此函数声明有误。
测试通过啊……
------解决方案--------------------
发现从某些全屏窗体切换过来,sendkey发送不成功,考虑是代码执行速度太快所致,修改下代码,让它有100ms的延时,测试通过。
Option Explicit
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long