简体   繁体   中英

How to show WebBrowser control context menu on left-click

WebBrowser control has a ContextMenuStrip property that can be set to a context menu. But this menu appears by right-click, how can I show it by left-click? There is no Click event for WebBrowser control and the MousePosition of WebBrowser.Document click event is not precise. It seems it depends on the element the mouse is over and also if the browser scrolls isn't shown in right place.

You can assign a handler to Click event or other mouse events of Document and show the context menu at Cursor.Position .

You can also prevent the default click action e.ReturnValue = false; .

private void webBrowser1_DocumentCompleted(object sender,
                                           WebBrowserDocumentCompletedEventArgs e)
{
    this.webBrowser1.Document.Click += Document_Click;
}

void Document_Click(object sender, HtmlElementEventArgs e)
{
    //To prevent the default click action you can uncomment next line:
    //e.ReturnValue = false;

    this.contextMenuStrip1.Show(Cursor.Position);
}

Here is some code for you. What you are looking for is doable with an event handler. If you need help please ask in comments.

this._browser.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
...
private void browser_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
{
    this._browser.Document.Body.MouseDown += new HtmlElementEventHandler(Body_MouseDown);
}
...
void Body_MouseDown(Object sender, HtmlElementEventArgs e)
{
    switch(e.MouseButtonsPressed)
    {
    case MouseButtons.Left:
        //your code
    break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM