如何以编程方式安全地关闭Google Chrome

use*_*858 7 .net c# google-chrome

如何通过C#安全地关闭谷歌浏览器?我可以杀死Chrome进程,但在这种情况下,Google Chrome会在下次运行时报告appcrash.

Sim*_*ier 9

您可以使用鲜为人知的UI Automation API,如下所示:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该在问题中说明*. (3认同)
  • 不幸的是,如果您打开了多个 chrome 窗口,这不会关闭第一个窗口。 (2认同)
  • 我不得不引用UIAutomationClient和UIAutomationTypes. (2认同)

Tho*_*mar 3

您可以尝试使用该类确定窗口句柄并向窗口Process发送消息。WM_CLOSE