Custom context menu for WPF WebBrowser Control

后端 未结 4 548
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 15:02

Hi I need to create a custom context menu for a web browser control in wpf. Here is my xaml code which is not working:



        
4条回答
  •  天涯浪人
    2021-01-21 15:44

    Hi You have to add reference to Microsoft HTML Object Library and than...

    XAML

    
      
        
          
          
          
        
      
        
            
        
    
    

    C#

    using System.Windows.Controls;
    using MSHTML;
    
    namespace WPFCustomContextMenuInWebBrowser {
      public partial class MainWindow {
        private HTMLDocumentEvents2_Event _docEvent;
        public MainWindow() {
          InitializeComponent();
          Wb.Navigate("http://google.com");
          Wb.LoadCompleted += delegate {
            if (_docEvent != null) {
              _docEvent.oncontextmenu -= _docEvent_oncontextmenu;
            }
            if (Wb.Document != null) {
              _docEvent = (HTMLDocumentEvents2_Event)Wb.Document;
              _docEvent.oncontextmenu += _docEvent_oncontextmenu;
            }
          };
        }
    
        bool _docEvent_oncontextmenu(IHTMLEventObj pEvtObj) {
          WbShowContextMenu();
          return false;
        }
    
        public void WbShowContextMenu() {
          ContextMenu cm = FindResource("MnuCustom") as ContextMenu;
          if (cm == null) return;
          cm.PlacementTarget = Wb;
          cm.IsOpen = true;
        }
      }
    }
    

提交回复
热议问题