【问题标题】:How do you override the ContextMenu that appears when right clicking on winforms WebBrowser Control?如何覆盖右键单击 winforms WebBrowser Control 时出现的 ContextMenu?
【发布时间】:2012-08-29 02:39:24
【问题描述】:

当您右键单击 WebBrowser 控件时,会出现带有“返回”、“查看源代码”等选项的标准 IE 上下文菜单。

如何让我自己的 ContextMenuStrip 出现? WebBrowser.ContextMenuStrip 不适用于此控件。

【问题讨论】:

    标签: .net winforms browser contextmenu


    【解决方案1】:

    这个站点上的许多其他解决方案听起来好像很难做到,因为它是一个 COM 对象......并建议添加一个新类“ExtendedWebBrowser”。对于这个任务,它变得非常简单。

    在添加 Web 浏览器控件的代码中,添加 DocumentCompleted 事件处理程序。

        WebBrowser webBrowser1 = new WebBrowser();
        webBrowser1.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    

    定义这些事件处理程序(更改 contextMenuStrip 以匹配您创建的事件处理程序的名称)。

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser browser = (WebBrowser) sender;
            browser.Document.ContextMenuShowing += new HtmlElementEventHandler(Document_ContextMenuShowing);
        }
    
        void Document_ContextMenuShowing(object sender, HtmlElementEventArgs e)
        {
            // If shift is held when right clicking we show the default IE control.
            e.ReturnValue = e.ShiftKeyPressed; // Only shows ContextMenu if shift key is pressed. 
    
            // If shift wasn't held, we show our own ContextMenuStrip
            if (!e.ReturnValue)
            {
                // All the MousePosition events seemed returned the offset from the form.  But, was then showed relative to Screen.
                contextMenuStripHtmlRightClick.Show(this, this.Location.X + e.MousePosition.X, this.Location.Y + e.MousePosition.Y); // make it offset of form
            }
        }
    

    注意:我的覆盖执行以下操作: * 如果右键单击时按住 shift 键,则显示 IE 返回值。 * 否则显示 contextMenuStripHtmlRightClick(本例中未显示定义)

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2011-06-16
      • 2022-12-23
      • 2011-11-21
      • 2011-07-20
      • 2018-07-25
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多