Sunday, August 10, 2025

Weird issues in WebView2 / WinUI3: handling the ALT key

Applies to: WinUI3 apps with a WebView2 and a menu

Problem: Normally users press the "Alt" ("Menu") key to use an app's menu. But after the user clicks on a WebView2 (as one does; it's a common practice), all Alt keys will be swallowed up by the WebView2.

Solution: capture the 'Alt' key and use that as a trigger to move focus. 

  1. In the JavaScript for the one specific page I use, add a 'keydown' event listener. When the event.key is "Alt", send a special message to the enclosing C# code using the  window.chrome.webview.postMessage method.
  2. In the C# code add a WebMessageReceived event callback. When the special message is received, set the app's focus to the parent object (cast the this.Parent to a FrameworkElement)    

The problem with this solution is that the first ALT is entirely swallowed up. The user has to press ALT twice to use the menus, but only when they have clicked on the WebView2.

Interesting discoveries: weirdly, when I wrote the C# code, Visual Studio 2022 hallucinated up a solution that involved constructing real objects like a KeyRoutedEventArgs and then calling made-up methods. And, FYI, the KeyRoutedEventArg has no public constructor. 

Links:

KeyRoutedEventArgs  Random difficult work-around and this one, too 

So many issues: 721 3352  984 5772 288 951 

No comments: