How to safely close Google Chrome programmatically

后端 未结 2 1491
时光取名叫无心
时光取名叫无心 2021-01-02 11:56

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.

2条回答
  •  再見小時候
    2021-01-02 12:33

    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();
            }
        }
    }
    

提交回复
热议问题