none
How to get handle of chrome browser window RRS feed

  • Question

  • programmatically i want to get handle of chrome browser window. when user open chrome browser and select text in any open tab and click a button on my c# winform then i want to store those selected text of chrome browser windows in clip board. how to do it...guide me with code.

    i got few links but not very clear 

    https://blog.jayway.com/2013/02/06/how-to-get-selected-text-from-another-windows-program/
    https://stackoverflow.com/questions/16958051/get-chrome-browser-title-using-c-sharp
    https://www.codeproject.com/Questions/219606/How-Can-I-Get-Title-of-a-Chrome-Processes
    https://stackoverflow.com/questions/18897070/getting-the-current-tabs-url-from-google-chrome-using-c-sharp
    http://www.vbforums.com/showthread.php?833281-SOLVED-FindWindow-function-to-find-Google-Chrome-personal-user-s-windows

    https://stackoverflow.com/questions/16958051/get-chrome-browser-title-using-c-sharp
    https://www.c-sharpcorner.com/forums/how-can-i-get-title-of-a-chrome-processes
    • Edited by Sudip_inn Thursday, September 5, 2019 11:05 AM
    Thursday, September 5, 2019 8:43 AM

Answers

  • Yes, it's absolutely free as NuGet packages.

    1. Selenium.WebDriver 

    2. Selenium.WebDriver.ChromeDriver 

    Add references and then only few lines of code will resolve your problem. You need to add a button or something to open the browser from your application.

    ChromeDriver chromeDriver;
    private void btnStartBrowser_Click(object sender, RoutedEventArgs e)
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArgument("disable-infobars");
        options.AddArgument("--start-maximized");
    
        chromeDriver = new ChromeDriver(options);
        chromeDriver.Navigate().GoToUrl("https://google.com/");
    }

    Next, you can navigate to any page from browser or directly change the URL from address bar. Then you can select and use your button to copy text.

    private void btnCopySelected_Click(object sender, RoutedEventArgs e)
    {
        IJavaScriptExecutor excutor = (IJavaScriptExecutor)chromeDriver;
        var selectedText = excutor.ExecuteScript("return window.getSelection().toString();");
        if(selectedText != null)
        {
            Clipboard.SetText((string)selectedText);
        }            
    }



    Avik Das

    • Marked as answer by Sudip_inn Monday, September 9, 2019 8:41 AM
    Sunday, September 8, 2019 8:25 AM
  • You asked:

    >then how could i send WM_COPY message to chrome browser
    >
    if i get that browser handle ? any sample code would be helpful.

    I gave you the sample code to do exactly that.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by Sudip_inn Tuesday, September 10, 2019 7:04 AM
    Tuesday, September 10, 2019 6:26 AM
  • @Sudip_inn you can add references like any other NuGet package, and don't need to download separately.

    Right click on your project name in solution explorer -

    

    Here is a tutorial, which you can check to begin. 

    Selenium covered under Apache 2.0 License, rest you can check. it's a free(open source) tool as per my understanding as of now. Few tools are developed based on it, so you have to check the terms & condition when you use them.


    Avik Das



    • Edited by D Avik Tuesday, September 10, 2019 7:56 AM
    • Marked as answer by Sudip_inn Tuesday, September 10, 2019 7:22 PM
    Tuesday, September 10, 2019 7:49 AM

All replies

  • programmatically i want to get handle of chrome browser window.

    For example =>

    IntPtr hWndChrome = IntPtr.Zero;
    Process[] processesChrome = Process.GetProcessesByName("chrome");
    if (processesChrome.Length > 0)
    {
        foreach (Process proc in processesChrome)
        {
            if (proc.MainWindowHandle == IntPtr.Zero)
                continue;
            else
            {
                hWndChrome = proc.MainWindowHandle;
                break;
            }
        }
    }
    if (hWndChrome != IntPtr.Zero)
    {                   
        // Code...
    
    }

    Thursday, September 5, 2019 11:16 AM
  • If this were a standard Windows GUI app, like Notepad, you could get the top-level window handle, then fetch the handle of the window with the keyboard focus, then send it a WM_COPY message to trigger a clipboard "copy" operation.  However, Chrome is not a standard Windows GUI app.  If you use an application like "spyxx" to look at its window, you'll see that the whole application is just one window.  There are no subwindows for the controls.  They do ALL of their own drawing, using their own custom controls that do not have individual window handles.  There's just no way to probe that way.

    The right answer is to alter your procedure.  Instead of "select text in any open tab and click a button on my c# winform", change it to "select text in any open tab, press Ctrl-C, and click a button in my c# winform".  That way, when your button is clicked, you'll KNOW that the text is already in the clipboard.  You don't have to poke around the insides of Chrome.

    (You can try sending a WM_COPY to the top-level Chrome window, but I doubt that will work.)


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Thursday, September 5, 2019 5:07 PM
  • sir if i get ahndle of chrome browser this way

    IntPtr hWndChrome = IntPtr.Zero;
    Process[] processesChrome = Process.GetProcessesByName("chrome");
    if (processesChrome.Length > 0)
    {
        foreach (Process proc in processesChrome)
        {
            if (proc.MainWindowHandle == IntPtr.Zero)
                continue;
            else
            {
                hWndChrome = proc.MainWindowHandle;
                break;
            }
        }
    }
    if (hWndChrome != IntPtr.Zero)
    {                   
        // Code...
    
    }
    then how could i send WM_COPY message to chrome browser if i get that browser handle ? any sample code would be helpful. thanks
    • Edited by Sudip_inn Thursday, September 5, 2019 6:56 PM
    Thursday, September 5, 2019 6:55 PM
  • You want to copy text from HTML document actually. You can try the tools like Selenium, which are popular for browser automation.

    You can hook different type of event and write your code in event handlers.


    Avik Das

    Thursday, September 5, 2019 7:35 PM
  • [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
    public const int WM_COPY = 0x0301;
    ...
    SendMessage( hWndChrome, WM_COPY, 0, 0 );


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Friday, September 6, 2019 12:27 AM
  • Probably the best solution is to write an extension that uses Native Messaging to communicate with your program. All major browsers support that solution with little or no differences.


    Sam Hobbs
    SimpleSamples.Info

    Friday, September 6, 2019 6:12 PM
  • i am not familiar with Selenium. is it free ? does it provide any free dll which i can add as reference in my project to interact with any browser?

    can you please provide some code by which i can open chrome browser by Selenium. when user select text from any tab of browser then i can pickup selected text from active tab from my c# code using Selenium?

    if possible please guide me with some link from where i can get the idea to reach my objective using Selenium from my c# project. thanks

    Saturday, September 7, 2019 7:29 PM
  • how to use native messaging from my c# code ? which dll i need to add ?

    my objective is to open chrome browser from my c# application and when user select any text from browser window and click on a button of my application then i want to store those selected text in clipboard. how to achieve it by  native messaging using c# ?

    some code example would be helpful for me. thanks

    Saturday, September 7, 2019 7:34 PM
  • sir you shared a code. please tell me what kind of operation your provided code will do ?

    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
    public const int WM_COPY = 0x0301;
    ...
    SendMessage( hWndChrome, WM_COPY, 0, 0 );

    Saturday, September 7, 2019 7:34 PM
  • Unfortunately, to use native messaging, there is much to learn about. The first thing is you need to understand browser extensions. Fortunately learning that will be very beneficial; you can use that knowledge and experience for many things. The good news is that all the major browsers use browser extensions the same, or at least close to the same. There are very many articles about browser extensions.

    The following are some articles that can help.

    If you have specific questions then I can probably help but please read some of those articles and read about browser extensions. It will take time to learn all that but then you will have a very useful solution.



    Sam Hobbs
    SimpleSamples.Info

    Saturday, September 7, 2019 9:02 PM
  • Yes, it's absolutely free as NuGet packages.

    1. Selenium.WebDriver 

    2. Selenium.WebDriver.ChromeDriver 

    Add references and then only few lines of code will resolve your problem. You need to add a button or something to open the browser from your application.

    ChromeDriver chromeDriver;
    private void btnStartBrowser_Click(object sender, RoutedEventArgs e)
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArgument("disable-infobars");
        options.AddArgument("--start-maximized");
    
        chromeDriver = new ChromeDriver(options);
        chromeDriver.Navigate().GoToUrl("https://google.com/");
    }

    Next, you can navigate to any page from browser or directly change the URL from address bar. Then you can select and use your button to copy text.

    private void btnCopySelected_Click(object sender, RoutedEventArgs e)
    {
        IJavaScriptExecutor excutor = (IJavaScriptExecutor)chromeDriver;
        var selectedText = excutor.ExecuteScript("return window.getSelection().toString();");
        if(selectedText != null)
        {
            Clipboard.SetText((string)selectedText);
        }            
    }



    Avik Das

    • Marked as answer by Sudip_inn Monday, September 9, 2019 8:41 AM
    Sunday, September 8, 2019 8:25 AM
  • sure i will test your code and let you know. thanks a lot for your help.
    Monday, September 9, 2019 8:41 AM
  • Please include right nuget link for web drive which i can download and test your code.
    Monday, September 9, 2019 7:24 PM
  • You asked:

    >then how could i send WM_COPY message to chrome browser
    >
    if i get that browser handle ? any sample code would be helpful.

    I gave you the sample code to do exactly that.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by Sudip_inn Tuesday, September 10, 2019 7:04 AM
    Tuesday, September 10, 2019 6:26 AM
  • @D Avik  should i download 2 nuget for webdrive ?

    Can you please give me few good tutorial links for web drive from where i can get knowledge to work with webdrive using c# for automation kind of task.

    selenium webdrive api is free ? because if i use now later it does not work and show message like Trial over then i will be in problem. can you please confirm or give me any link.

    looking forward for your reply. thanks



    • Edited by Sudip_inn Tuesday, September 10, 2019 7:09 AM
    Tuesday, September 10, 2019 7:07 AM
  • @Sudip_inn you can add references like any other NuGet package, and don't need to download separately.

    Right click on your project name in solution explorer -

    

    Here is a tutorial, which you can check to begin. 

    Selenium covered under Apache 2.0 License, rest you can check. it's a free(open source) tool as per my understanding as of now. Few tools are developed based on it, so you have to check the terms & condition when you use them.


    Avik Das



    • Edited by D Avik Tuesday, September 10, 2019 7:56 AM
    • Marked as answer by Sudip_inn Tuesday, September 10, 2019 7:22 PM
    Tuesday, September 10, 2019 7:49 AM
  • @Avik i tested your code and faced some issue.

    1) if target pc has no chrome browser install then how can i capture it by ChromeDriver ?

    2) when i am opening chrome browser by ChromeDriver instance then browser is opening but another CUI window is getting opened which i do not want to visible or i want to hide this CUI window. if it is not possible then how could i open this CUI window in minimize state ?

    a sample CUI window screen shot attached when i work with FirefoxDriver. the same occur when i work with ChromeDriver instance.

    3) when i executing this code chromeDriver.Close(); then opened chrome browser is getting closed but CUI window is still open. so if i click 5 times on open button then 5 CUI window is getting open which i need to manually close it....which i do not want to manually close it rather i want to close it when browser will be closed....how to achieve it ?

    4) how to capture from code that opened chrome browser is close by this code chromeDriver.Close(); or if user click on cross button of chrome browser to close it?

    5) how to open a new tab in already opened chrome browser instead of opening new chrome browser. if no chrome browser is open at all then new chrome browser will be open...how to achieve it by code. this below code opening new chrome browser always....what to change there for my point 5

    chromeDriver = new FirefoxDriver(options);
    
    chromeDriver.Navigate().GoToUrl("https://www.google.com");

    6) another issue occur when i work with chrome driver that. it open chrome browser but a notification appear on browser like Chrome is being controlled by automated test software

    i search google to hide it and found people said to use this option

    options.setExperimentalOption("excludeSwitches", new String[] { "enable-automation" });

    at my end this function does not available setExperimentalOption so what to do ?

    please guide me with answer point wise. thanks





    • Edited by Sudip_inn Friday, October 11, 2019 8:24 PM
    Friday, October 11, 2019 8:18 PM
  • i have done the job this way

    public class Browser : IDisposable
        {
            bool disposed = false;
            IWebDriver Driver;
            ChromeDriverService driverService;
    
            public Browser()
            {
                //Chrome Driver copied on startup path                
                driverService = ChromeDriverService.CreateDefaultService(Application.StartupPath, "chromedriver.exe");
    
                //hide driver service command prompt window
                driverService.HideCommandPromptWindow = true;
                ChromeOptions options = new ChromeOptions();
                options.AddArgument("disable-infobars");
                options.AddArgument("--start-maximized");
    
                //hide browser if you need              
                //options.AddArgument("headless");
                //or this to hiding browser
                //options.AddArgument("--window-position=-32000,-32000");
    
                Driver = new ChromeDriver(driverService, options);
            }
    
            public string GetSelectedText()
            {
                string strText = "";
    
                if (Driver!=null)
                {
                    IJavaScriptExecutor excutor = (IJavaScriptExecutor)Driver;
                    var selectedText = excutor.ExecuteScript("return window.getSelection().toString();");
                    if (selectedText != null)
                    {
                        //Clipboard.SetText((string)selectedText);
                        strText = (string)selectedText;
                    }   
                }
    
                return strText;
            }
    
            public void OpenSite(string strurl)
            {
                if (strurl != "")
                {
                    if (Driver != null)
                        Driver.Navigate().GoToUrl(strurl);
                }
            }
    
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
    
            protected virtual void Dispose(bool disposing)
            {
                if (disposed)
                    return;
    
                if (disposing)
                {
                    if (Driver != null)
                    {
                        try
                        {
                            Driver.Close();
                            Driver.Quit();
                            Driver.Dispose();
                            driverService.Dispose();
                        }
                        catch(Exception ex)
                        {
                            Driver.Quit();
                            Driver.Dispose();
                            driverService.Dispose();
                        }
                    }
                }
    
                disposed = true;
            }
        } 

    Sunday, October 13, 2019 7:30 PM