简体   繁体   中英

capturing highlighted text from a web browser using c#

I have a project that needs to capture highlighted text from a web browser(chrome, firefox etc.). In my project, the user highlights a text, for example a word from a web browser. And the program translates the word to the language that selected before using google translate. I have managed to capture highlighted text from some applications like notepad, but I especially need to do that with web browsers.

Could anybody help me with that. I searched all of the documents and tried all of the approaches but I couldn't achieve my goal. The project is for my college to graduate.

I would greatly appreciate some help here. Thank you!

Put this on top of your class:

    [DllImport("user32.dll")]
    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);        

Then a method to recieve text.

    static uint KEYEVENTF_KEYUP = 2;
    static byte VK_CONTROL = 0x11;
   public static string gettext()
    {
        string message;
        try
        {
            Thread.Sleep(100);
            message=Clipboard.GetText();
            return message;
        }
        catch(Exception)
        {
            gettext();
        }
    }
   public static string highlightedtext()
    {
       string output;
       keybd_event(VK_CONTROL,0,0,0);
       keybd_event (0x43, 0, 0, 0 ); 
       keybd_event (0x43, 0, KEYEVENTF_KEYUP, 0);
       keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
       output=gettext();
       return output;
    }

NOTE: Sometimes the clipboard is in use and will give exception so you need try and catch , If it catch exception , do it again until it's not.

Advantage of using these code.:

1.If you just want something in the clipboard , call gettext()

2For highlighted text , call highlightedtext()

Anyone see errors please edit my post.

Thank you

EDIT!!: Adding static is use for main(). If you aren't use with main, Remove static

Edit2!!:Adding static for all outside variables!! Please tell me any more error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM