IE10中的JavaScript键盘事件

我一直在试图获得一个VBA脚本来分派一个keydown事件,但没有成功…没有太多的信息,以及在InternetExplorer的“iniKeyboardEvent”工作。

Sub ie_evt() Dim ie As InternetExplorer Dim doc As HTMLDocument Set ie = CreateObject("InternetExplorer.Application") ie.Navigate "http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onkeydown.htm" Do While ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE DoEvents Loop ie.Visible = True Set doc = ie.Document doc.parentWindow.execScript ("var tb = document.getElementById('oExample')") doc.parentWindow.execScript ("tb.value = 'a'") doc.parentWindow.execScript ("var e = document.createEvent('KeyboardEvent')") doc.parentWindow.execScript ("e.initKeyboardEvent('keydown', true, true, window, false, false, false, false, 65, 0);") doc.parentWindow.execScript ("tb.dispatchEvent(e)") End Sub 

任何人都可以帮我吗?

谢谢

在VBA中,这总是诡计多端,但是您可以尝试使用Win API将键盘事件发送到活动窗口。 2要点:

  • 确保发送键事件时IE窗口是活动窗口(您可以使用AppActivate()或其他API方法来执行此操作)

  • 您需要知道您想要按“按”的键的虚拟键码是其中大部分的列表

然后在标准的代码模块中这样的东西:

 #If Win64 Then Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) #Else Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) #End If '// Example, send the number 5 Const NUM_5 As Byte = &H65 Sub foo() '// your code here - ensure IE window is active window and then: '// Send key press event keybd_event NUM_5, 0&, 0&, 0& '// rest of code End Sub