Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser keyboard shortcuts

I have a WebBrowser control displaying some HTML.
I want the user to be able to copy the entire document, but not do anything else.

I've set the IsWebBrowserContextMenuEnabled and WebBrowserShortcutsEnabled properties to false, and I want to handle KeyUp and run some code when the user presses Ctrl+C.

How can I do that?
The WebBrowser control doesn't support keyboard events.
I tried using the form's KeyUp event with KeyPreview, but it didn't fire at all.

EDIT: Here's my solution, inspired by Jerb's answer.

class CopyableWebBrowser : WebBrowser {
    public override bool PreProcessMessage(ref Message msg) {
        if (msg.Msg == 0x101    //WM_KEYUP
         && msg.WParam.ToInt32() == (int)Keys.C && ModifierKeys == Keys.Control) {
            DoCopy();
            return true;
        }
        return base.PreProcessMessage(ref msg);
    }
    void DoCopy() {
        Document.ExecCommand("SelectAll", false, null);
        Document.ExecCommand("Copy", false, null);
        Document.ExecCommand("Unselect", false, null);
    }
}
like image 257
SLaks Avatar asked Dec 30 '09 14:12

SLaks


People also ask

How do I see all keyboard shortcuts?

Press Ctrl + Alt + ? on your keyboard.


2 Answers

You could try this method as well. Put it in your main form area and it should catch all of the keyboard commands. I use it to add keyboard shortcuts to dynamically created tabs.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    switch (keyData)
    {
        case Keys.Control|Keys.Tab:
            NextTab();
            return true;
        case Keys.Control|Keys.Shift|Keys.Tab:
            PreviousTab();
            return true;
        case Keys.Control|Keys.N:
            CreateConnection(null);
            return true;
    }
    return false;
like image 116
Jerb Avatar answered Oct 01 '22 09:10

Jerb


It is a bug in Windows Forms. Its IDocHostUIHandler.TranslateAccelerator implementation actually tries to send the keystroke to the ActiveX host by returning S_OK after checking WebBrowserShortcutsEnabled and comparing the key data to predefined shortcuts. unfortunately in Windows Forms's keyboard processing, the shortcutkey property is checked during ProcessCmdKey, which means IDocHostUIHandler.TranslateAccelerator returned a little bit too late. That causes anything in the Shortcut enum (e.g. Control+C, Del, Control+N etc) stops working when WebBrowserShortcutsEnabled is set to false.

You can create or find a webbrowser ActiveX wrapper class (e.g. csexwb2) that provides a different IDocHostUIHandler.TranslateAccelerator implementation to check shortcut keys again. The Windows Forms webbrowser control does not allow customizing its IDocHostUIHandler implementation.

like image 44
5 revs Avatar answered Oct 01 '22 10:10

5 revs