开发者

Get Selected text in browser programmatically

开发者 https://www.devze.com 2022-12-15 21:40 出处:网络
From my windows application, i want to detect selected text in \"Internet Explorer\", Firefox and any other browser.

From my windows application, i want to detect selected text in "Internet Explorer", Firefox and any other browser.

Do you know what piece of code should i use in order to achieve this?

The idea is not to search for a text in IE, but instead "capture the selected text" in IE. By the way not only IE, but any windows application that has the focus One thing i can think of is to simulate a ctrl+c to copy selected text and then read the clipboard, but i don't like this solution either.

Im almost sure there should be a way to get the selected text using Windows API, i know t开发者_如何学Gohat using EM_GETSELTEXT, WM_GETTEXT, EM_GETSEL might be useful, but they do not work in IE or any other browser, here is my problem....


This is a rather tall order. I think you may only have a slim chance of achieving this with IE, where you can load the same page as is loaded in the 'outside' browser into a WebBrowser control, and get the selected text. To the best of my knowledge, and on advice from someone who has long sought to do something like this, there is just no automation model for Firefox that is accessible to C# code without gargantuan effort and risk.

Do you have any control over the page? You might consider injecting something like jQuery to post the selection using an Ajax call, and set up a server to listen for that call.


I would suggest that you look into using the WatiN API to test a web page for the presence of a specific string. WatiN currently supports IE 6, 7 and 8, and a CTP version exists for testing with Firefox 2.x and 3.x. This article describes how to use WatiN to search for a piece of text in a web page, and there is documentation on the WatiN site describing how to call WatiN from your application.

An initial starting point for your code would be:

using System;
using WatiN.Core;

public static class WatiNExample
{

    public static bool CheckUrlForText(string p_sUrl, string p_sText)
    {
        // Open a new Internet Explorer window and
        // go to the google website.
        IE ie = new IE(p_sUrl);

        try    
        {
            return ie.Text.Contains(p_sText));
        }
        finally
        {
            ie.Close();
        }
    }
}


VB Script is a way to achieve that, but only in IE and only to copy (all web page) in clipboard. Then, you could paste it and manipulate the string thus retrieved in any application you like.

Option Explicit <br>
Dim objShell <br>
Set objShell=CreateObject("WScript.Shell") <br>
objShell.Run "iexplore.exe http://www.google.com" ' or whatever page you need to copy from <br>
WScript.Sleep 7000 ' just to wait IE to load the page <br>
objShell.SendKeys "^a" ' selects all <br>
objShell.SendKeys "^c" ' copy into clipboard <br>
0

精彩评论

暂无评论...
验证码 换一张
取 消