Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

winforms - Retrieving Selected Text from Webbrowser control in .net(C#)

I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.

I appreciate any help or resources regarding this.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.

To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at "C:Program FilesMicrosoft.NETPrimary Interop AssembliesMicrosoft.mshtml.dll". There may be more than one, make sure you choose the reference with this path.

Then to get the current text selection, for example:

using mshtml;

...

    IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;

    IHTMLSelectionObject currentSelection= htmlDocument.selection;

    if (currentSelection!=null) 
    {
        IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;

        if (range != null)
        {
            MessageBox.Show(range.text);
        }
    }

For more information on accessing the full DOM from a .NET application, see:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...