2014-12-03 69 views
0

我有一個包含WebBrowser和上下文菜單的窗體。C#Webbrowser複製

如果用戶沒有通過鼠標選擇(高亮顯示)頁面中的任何文本,我想禁用上下文菜單中的複製功能。

我試圖用

IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; 
if (range != null || range.text.Trim() != "") 
    { 
     MessageBox.Show(range.text); 
     copyToolStripMenuItem.Enabled = true; 
    } 
    else 
    { 
     copyToolStripMenuItem.Enabled = false; 
    } 

但它並沒有爲我工作。

Error: Empty Selection

Selected Text Display Correctly

回答

0

我得到這個問題的答案調試應用程序

這是如果有人需要它

問題是range.text!=「無效後, 「< - null此處爲字符串

private void contextMenu_Opening(object sender, CancelEventArgs e) 
     { 
      if (Clipboard.GetDataObject().GetFormats()[0] == System.Windows.Forms.DataFormats.StringFormat) 
      { 
       pasteToolStripMenuItem.Enabled = true; 
      } 
      else 
      { 
       pasteToolStripMenuItem.Enabled = false; 
      } 

      IHTMLDocument2 htmlDocument = MainBrowser.Document.DomDocument as IHTMLDocument2; 
      IHTMLSelectionObject currentSelection = htmlDocument.selection; 
      if (currentSelection.type == "Text") 
      { 
       IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; 
       if (range.text != "null" || !String.IsNullOrEmpty(range.text.Trim())) 
       { 
        copyToolStripMenuItem.Enabled = true; 
       } 
       else 
       { 
        copyToolStripMenuItem.Enabled = false; 
       } 
      } 
      else 
      { 
       copyToolStripMenuItem.Enabled = false; 
      } 
     }