【问题标题】:.NET WebBrowser control - get active contextmenu.NET WebBrowser 控件 - 获取活动上下文菜单
【发布时间】:2011-06-16 14:49:08
【问题描述】:

我有 WebBrowser 控件,我希望在单击右键并出现上下文菜单时获取该上下文菜单的句柄。

这可能吗?

【问题讨论】:

    标签: c# browser contextmenu handle


    【解决方案1】:

    是的。

    您可以参考以下代码。

        //this code assumes WebBrowser object(_webBrowser) is already initiated
        //in class scope.
    
        //this method is needed to execute when form is loaded.
        //Register it to load event
        private void Loaded(object sender, RoutedEventArgs e)
        {
            _webBrowser.LoadCompleted += _webBrowser_LoadCompleted;
        }
    
        private HTMLDocumentEvents2_Event _docEvent;
    
        private void _webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (_docEvent != null)
            {
                _docEvent.oncontextmenu -= new HTMLDocumentEvents2_oncontextmenuEventHandler(_docEvent_oncontextmenu);
            }
            if (_webBrowser.Document != null)
            {
                _docEvent = (HTMLDocumentEvents2_Event)_webBrowser.Document;
                _docEvent.oncontextmenu += new HTMLDocumentEvents2_oncontextmenuEventHandler(_docEvent_oncontextmenu);
            }
        }
    
        bool _docEvent_oncontextmenu(IHTMLEventObj pEvtObj)
        {
            //do something and determine you want whether context menu shows or not
            //if you want to shows context menu, you'll need to return true.
            return true;
        }
    

    【讨论】:

    • 此处出现错误:docEvent = (HTMLDocumentEvents2_Event)_webBrowser.Document;无法将类型“System.Windows.Forms.HtmlDocument”转换为“mshtml.HTMLDocumentEvents2_Event
    • 糟糕!很抱歉烦人。我提到了 WPF WebBrowser。在 Winform WebBrowser,您可以使用 _webBrowser.Document.DomDocument。
    • 您需要在 WinForm 中使用 DocumentCompleted 事件,而不是 WPF 中的 LoadCompleted 事件。
    • 但是现在如何获取该上下文菜单的项目?
    • 如果我也能回答这个问题,我会很高兴。但是,访问上下文菜单并不容易,因为 WinForm 中 WebBrowser 的基础不是托管对象。
    【解决方案2】:

    如果您只想显示自己的 contextMenu。我在这里发布了一个适用于 winforms WebBrowser 控件的解决方案:

    How do you override the ContextMenu that appears when right clicking on winforms WebBrowser Control?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多