How to safely close Google Chrome programmatically

后端 未结 2 1492
时光取名叫无心
时光取名叫无心 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 try to determine the window handle(s) using the Process class and send a WM_CLOSE message to the window.

    0 讨论(0)
  • 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题