I noticed that the "KeyUp" event captures only some of the keys (up, down, left, right, Ctrl, escape). In WebBrowser, that event captures all the keys in the keyboard. How do we add the event that adds a key pressed or released?
Thanks
WebView2 mywebView = new WebView2();
mywebView.KeyUp += MywebView_KeyUp;
In WebView2, you have to add onkeyup
attribute to the input tag in HTML. When a key is pressed, a javascript method needs to be called to handle the event or send a "webmessage" back to the host to handle it.
This is what I did to get the "keyup" event work in WebView2:
Define "onkeyup" event for the input tag (I use an HtmlTextWriter but it should not matter). I call the javascript method named "CallHost"
htmlWriter.AddAttribute("onkeyup", "CallHost(this);");
Send a response message back to the host (this will be captured by the "WebMessageReceived" event in C#):
function CallHost(element)
{
window.chrome.webview.postMessage(
JSON.stringify({
ElementId: element.id,
Type: element.tagName,
Name: element.name,
Value: element.value
})
);
}
C# event handler:
private void MyWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
MyWebMessage message = JsonConvert.DeserializeObject<MyWebMessage>(args.TryGetWebMessageAsString());
/*handle keyup*/
}