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.
Asked
Active
Viewed 1.1k times
8
-
Get a handle to Chrome's windows and send `WM_CLOSE` to each of them: http://stackoverflow.com/questions/1129204/how-to-use-wm-close-in-c – Jon Jan 23 '13 at 12:28
-
Have a look at this http://stackoverflow.com/questions/2055753/how-to-gracefully-terminate-a-process – Justin Harvey Jan 23 '13 at 12:29
-
I am just curious... by default google chrome or any other browser would alert me that an application is trying to close the browser? Thinking as a user I think this is a very annoying process. Most of the time I have so many tab´s opened and I just don´t want to close everything. As each tab has its own process, would not be better to close a specific tab instead of the whole browser? – Guilherme Longo Jan 23 '13 at 12:34
-
@Guilherme I need to close browser, because I need to modify SQLite Chrome database(set my default search provider). – user2003858 Jan 23 '13 at 12:43
-
I did not know we could manipulate Chrome database. Now that you said it make sense that you close the browser. – Guilherme Longo Jan 23 '13 at 13:10
2 Answers
10
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();
}
}
}

Simon Mourier
- 132,049
- 21
- 248
- 298
-
-
3
-
2Unfortunatly if you have multiple chrome windows open this will not close the first one. – KVM Dec 01 '13 at 21:46
-
1Worked well for me!! Thanks Simon. Namespaces required: using System.Diagnostics, using System.Windows.Automation – Tom Martin Mar 10 '16 at 18:15
-
2
3
You could try to determine the window handle(s) using the Process
class and send a WM_CLOSE
message to the window.

Thorsten Dittmar
- 55,956
- 8
- 91
- 139