C#Webbrowser Copy

时间:2014-12-03 09:41:59

标签: c# text mouse selection

我有一个包含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

1 个答案:

答案 0 :(得分:0)

调试应用程序后,我得到了这个问题的答案

如果有人需要它

问题是range.text!=" null" < - 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;
            }
        }
相关问题