Alex Rivera | Logout

WebBrowser keyboard shortcuts

Asked 2009-12-30T14:41:33.470
9

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);
    }
}
Edit
Report

1 Answer

10

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;
answered 2009-12-30T18:38:12.383

Your Answer