WPF Catch Ctrl + N Not Working
-
14-07-2021 - |
سؤال
Hello and thank you for reading.
I have an embedded WebBrowser in a Kiosk style WPF application and I am attempting to prevent the user from being able to use the Ctrl + O or Ctrl + N keyboard shortcuts to circumvent the page that I have limited them to.
Here is my code which is in the top most window of the application:
// This is in the constructor of the window under InitializeComponent();
AddHandler(Keyboard.PreviewKeyDownEvent, (System.Windows.Input.KeyEventHandler)HandleKeyDownEvent);
private void HandleKeyDownEvent(object sender, System.Windows.Input.KeyEventArgs e)
{
Key key = (e.Key == Key.System) ? e.SystemKey : e.Key;
if(e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
switch(key)
{
case Key.N:
case Key.O:
case Key.P:
MessageBox.Show("BOOM");
break;
}
}
}
The event handler is properly triggering when I press Ctrl + N, but e.Key is Key.Control not Key.N. It appears that the event triggers immediately when the Ctrl button is pressed (as expected), but fails to capture the N key. I have tried using Keyboard.IsKeyDown(Key.N) and that returns false as well.
Any advice or suggestions are welcome.
Thanks,
Adam
EDIT: I have also tried to prevent a new window using the NewWindow, NewWindow2 and NewWindow3 events on the browser itself. No luck there either.
المحلول
Well I feel like a complete numb skull! Turns out it is as simple as adding the following line of code. I hope this helps other people that may be trying very overcomplicated solutions like I was.
browser.WebBrowserShortcutsEnabled = false;