Disable Shortcuts in WebBrowser Control and keep Copy and Paste
It took me a while to figure this one out (admittedly it shouldn’t have taken as long as it did!), so hopefully this will save someone else banging their head against the desk if they run into the same issue.
I have a WebBrowser control which navigates to about:blank and then loads HTML into the document from an embedded resource and then is altered afterwards to show incoming data. As this document is being built in real time, it causes issues when the user hits the F5 key, as it refreshes about:blank and shows them a blank screen again.
My initial solution to this was to just set the WebBrowserShortcutsEnabled property to false, gave it a test, it stopped it refreshing, all was good with the world again! Or not…
The WebBrowserShortcutsEnabled property will also disable CTRL+C and CTRL+V, although I don’t need the paste shortcut, I do need the copy shortcut.
The solution is actually very simple, and I’m not sure why it took so long to come to the conclusion (I blame lack of Red Bull flowing through my veins!). But again – in case anyone is banging their heads against their desk, this is what you need to do:
Set the WebBrowserShortcutsEnabled property to false as previously mentioned and create an event handler for the PreviewKeyDown event of the WebBrowser control and add the code below to it
if ((e.Modifiers == Keys.Control) && (e.KeyCode == Keys.C))
webBrowser1.Document.ExecCommand("Copy", false, null);
If you need to add more functionality back (i.e. cut and paste), the ExecCommand method also accepts Cut and Paste as commands, so just repeat the code above to pick up the X and V keys too and execute the appropriate command.
If also like me, you need to stop the user from navigating to another page from within your WebBrowser control, add an event handler for the Navigating event of your WebBrowser control and add the following:
e.Cancel = true;
if ((webBrowser1.Tag != null) && (webBrowser1.Tag.Equals(true)))
e.Cancel = true;
This will force all pages to open in a new window, and if you set the Tag property to be true after you have loaded your initial content into the page, will prevent a link to about:blank sending the user back to a blank page!
2 Comments + Add Comment
Got anything to say? Go ahead and leave a comment!
- Adding Both Undo and Redo Functionality to the .NET TextBox
- Setting Default CurrentCulture in all Versions of .NET
- Capturing Network Traffic using the WiFi Pineapple, tcpdump and Android
- Disable Shortcuts in WebBrowser Control and keep Copy and Paste
- Cracking PPTP / MS-CHAPv2 with Chapcrack & CloudCracker
- int0x90 on Disable Shortcuts in WebBrowser Control and keep Copy and Paste
- Olivier Jaquemet on Disable Shortcuts in WebBrowser Control and keep Copy and Paste
- ponix on Kid Teaches How to Use Tracert – Fail!
- kat on Final Fantasy XIII: How to Beat Odin
- JD Swagger on Final Fantasy XIII: How to Beat Odin