Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Window handle (IntPtr) from Selenium webdriver's current window GUID

I'm trying to capture a screenshot of whole browser screen (e.g. with any toolbars, panels and so on) not only an entire page, so I'm got this code:

using (FirefoxDriver driver = new FirefoxDriver())
{ 
    driver.Navigate().GoToUrl(url);                

    ScreenCapture sc = new ScreenCapture();

    // How can I find natural IntPtr handle of window here, using GUID-like identifier returning by driver.currentWindowHandle?
    Image img = sc.CaptureWindow(...);
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Jpeg);
    return new FileStreamResult(ms, "image/jpeg");
}
like image 211
kseen Avatar asked Jul 17 '12 15:07

kseen


Video Answer


2 Answers

You could get the window handle using Process.GetProcesses:

using (FirefoxDriver driver = new FirefoxDriver())
{
    driver.Navigate().GoToUrl(url);

    string title = String.Format("{0} - Mozilla Firefox", driver.Title);
    var process = Process.GetProcesses()
        .FirstOrDefault(x => x.MainWindowTitle == title);

    if (process != null)
    {
        var screenCapture = new ScreenCapture();
        var image = screenCapture.CaptureWindow(process.MainWindowHandle);
        // ...
    }
}

This of course assumes that you have a single browser instance with that specific title.

like image 105
Paolo Moretti Avatar answered Sep 16 '22 23:09

Paolo Moretti


Just and idea for hack. You may use Reflection methods to get process of firefox instance. First declare FirefoxDriverEx class inherited from FirefoxDriver - to access protected Binary property which encapsulates Process instance:

 class FirefoxDriverEx : FirefoxDriver {
        public Process GetFirefoxProcess() {
            var fi = typeof(FirefoxBinary).GetField("process", BindingFlags.NonPublic | BindingFlags.Instance);
            return fi.GetValue(this.Binary) as Process;
        }
    }

Than you may get process instance for access to MainWindowHandle property

using (var driver = new FirefoxDriverEx()) {
            driver.Navigate().GoToUrl(url);

            var process = driver.GetFirefoxProcess();
            if (process != null) {
                var screenCapture = new ScreenCapture();
                var image = screenCapture.CaptureWindow(process.MainWindowHandle);
                // ...
            }
        }
like image 43
necrostaz Avatar answered Sep 16 '22 23:09

necrostaz