2012-08-29 61 views

回答

5

在這個網站上的很多其他解決方案使它聽起來很難做,因爲它是一個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 
     } 
    } 

注:我重寫執行以下操作: *如果移按住當你右擊它顯示了IE瀏覽器的返回值。 *否則顯示contextMenuStripHtmlRightClick(定義未在此示例中顯示)