Custom context menu for WPF WebBrowser Control

后端 未结 4 587
爱一瞬间的悲伤
爱一瞬间的悲伤 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:31

    I've taken the solution provided by @MartinHoly and i've encountered the problem: to context menu can be popped up only once (if you right-click on the scrollbar, for example, or select a custom menu item - next time you right-click the WebBrowser brings the standard IE menu). I have made the following workaround: The xaml:

    
    
        
          
          
          
        
      
    
        
    
    

    The code behind:

    using System.Windows.Controls;
    using MSHTML;
    
    namespace WPFCustomContextMenuInWebBrowser {
      public partial class MainWindow {
    
        public MainWindow() 
        {
          InitializeComponent();
          Browser.LoadCompleted += BrowserOnLoadCompleted;
        }
    
        void BrowserOnLoadCompleted(object sender, NavigationEventArgs navigationEventArgs)
        {
            var mshtmlDoc = Browser.Document as HTMLDocument;
            if (mshtmlDoc == null) return;
                        var doc2event = mshtmlDoc as HTMLDocumentEvents2_Event;
            if (doc2event != null)
            {               
                doc2event.onfocusin += FocusInContextMenu;
            }            
        }
    
        bool OpenContextMenu(IHTMLEventObj pEvtObj)
        {
            WbShowContextMenu(pEvtObj as ContextMenu);
            return false;
        }
    
        void FocusInContextMenu(IHTMLEventObj pevtobj)
        {
            var mshtmlDoc = Browser.Document as HTMLDocument;
            var doc2event = mshtmlDoc as HTMLDocumentEvents2_Event;
            if (doc2event != null)
            {
                doc2event.oncontextmenu -= OpenContextMenu;
                doc2event.onfocusin -= FocusInContextMenu;
                doc2event.oncontextmenu += OpenContextMenu;
                doc2event.onfocusin += FocusInContextMenu;
            }
        }
    
        public void WbShowContextMenu() 
        {
          ContextMenu cm = FindResource("MnuCustom") as ContextMenu;
          if (cm == null) return;
          cm.PlacementTarget = Browser;
          cm.IsOpen = true;
        }
      }
    }
    

提交回复
热议问题