简体   繁体   中英

How to automatically close selenium chromedriver when Windows Form application closes or stops responding?

I want to make the selenium chromedriver close automatically when my windows form or program is closed, or stops responding. The chromedriver.exe should be dependent on the Windows Form application.

I am using a C# Windows Form application to automate a browsing task using Selenium chromedriver . I already found a question similar to this, except that I not only want the webdriver to close on form closing event, but also when the programs fails due to a bug or something.

In my case, I have hidden the console window of chromedriver.exe, so when the program fails, a zombie process is hidden in the processes, which I have to kill manually from the task manager. I have used this line in my code:

chromeDriverService.HideCommandPromptWindow = true;

I had a similar issue though with the Firefox Selenium browser. Within your form.cs, you can override the method OnFormClosing as such:

 protected override void OnFormClosing(FormClosingEventArgs e)
 {
     base.OnFormClosing(e);
     CloseBrowser();
 }

The CloseBrowser method:

 public void CloseBrowser()
 {
     driver.Close();
     driver.Dispose();
     driver.Quit();
 }

This is for Firefox but I'm fairly certain this code will work with the Chrome driver too! As for closing upon your program not responding, you could place the same CloseBrowser within the Catch clause of a Try/Catch, meaning if an exception occured, the browser would close.

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