Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely close Google Chrome programmatically

How can i safely close google chrome via C#? I can kill chrome process, but in this case Google Chrome will report appcrash on next run.

like image 970
user2003858 Avatar asked Jan 23 '13 12:01

user2003858


People also ask

How do I close a tab in Chrome programmatically?

close(); being executed? If you are developing a chrome extension then you can use the chrome API to close a specific tab which will should work in every case. You can also redirect to some other site or a random URL and have a script close that.

How do I completely shut down Google Chrome?

Click the “≡” button in the upper right corner of the Chrome browser window. Select the Exit button.

How do I kill Chrome in Task Manager?

Open cmd with "Run as Administrator." option (Use right-click to get the menu). Use the command tasklist to list all processes. Use the command taskkill /F /IM "chrome.exe" /T to terminate all its processes.


2 Answers

You could use the little known UI Automation API, like this:

static void CloseAllChromeBrowsers()
{
    foreach (Process process in Process.GetProcessesByName("chrome"))
    {
        if (process.MainWindowHandle == IntPtr.Zero) // some have no UI
            continue;

        AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
        if (element != null)
        {
            ((WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern)).Close();
        }
    }
}
like image 109
Simon Mourier Avatar answered Nov 15 '22 15:11

Simon Mourier


You could try to determine the window handle(s) using the Process class and send a WM_CLOSE message to the window.

like image 36
Thorsten Dittmar Avatar answered Nov 15 '22 14:11

Thorsten Dittmar