如果在用戶表單中使用 WebBrowser,有沒有辦法知道按下了什么鍵?
提前致謝 :)
編輯:我基本上想在 KeyDown 上打開一個不同的用戶表單,但 WebBrowser 阻止了它。也許我可以從 WebBrowser 運行我的 UserForm 的 Sub。
uj5u.com熱心網友回復:
好的,這是一個非常基本的示例,顯示您可以從 VBA 向 HTML 頁面發送訊息,并在另一個方向發送訊息:
用戶表單:
Option Explicit
Dim obj As webEvents 'must be Global to remain in scope...
'send a message to the browser page
Private Sub CommandButton1_Click()
'would need to escape the text sent if it contains (eg) '
Me.WebBrowser1.Document.parentWindow.execScript "MessageIn('" & Me.TextBox1.Text & "')"
End Sub
'receive a message from the browser page
Public Sub HandleBrowserMessage(s As String)
MsgBox "From web:" & vbLf & s
End Sub
Private Sub UserForm_Initialize()
Me.WebBrowser1.Navigate "about:blank" 'load a blank document
Application.Wait Now TimeSerial(0, 0, 1)
With Me.WebBrowser1.Document 'load some HTML
.Open "text/html"
.write Sheet1.Range("A1").Value
.Close
End With
Set obj = New webEvents 'new class instance
Set obj.ParentForm = Me 'for the callback
Set obj.HtmlOutput = Me.WebBrowser1.Document.getElementById("msgOut")
End Sub
類模塊webEvents:
Option Explicit
Public ParentForm As Object 'not As userform!
Public WithEvents HtmlOutput As MSHTML.HTMLInputElement
'handling click since change seems unreliable
Private Function HtmlOutput_onclick() As Boolean
ParentForm.HandleBrowserMessage CStr(HtmlOutput.Value)
End Function
單元格 A1 中的 HTML:
<html><body>
<input type="hidden" id="msgOut" /><br>
To VBA: <input type="text" size="20" id="msg" />
<button onclick="MessageOut()">Send to VBA</button><br><br>
From VBA: <span id="showMessage" style="color:#F00"></span><br>
<script>
function MessageIn(s){ document.getElementById("showMessage").innerText = s; }
function MessageOut(s){
var el = document.getElementById("msgOut");
el.value = document.getElementById("msg").value;
el.click();
}
</script>
</body></html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442627.html
標籤:javascript 擅长 vba
