using C# to close Google chrome incognito windows only

余生颓废 提交于 2019-12-10 18:04:21

问题


I wanted to create a small program to close google incogneto windows.

I have the code to kill ALL chrome windows but im not sure how to isolate just the incognito windows

existing code:

        Process[] proc = Process.GetProcessesByName("MyApp");
        foreach (Process prs in proc)
        {
            prs.Kill();
        }

回答1:


I played around with this a little but didn't have complete success. I was able to determine which windows were incognito, and from there, technically kill the process.

However, it appears the chrome executable has to be killed to close the actual window, which unfortunately closes all the chrome windows.

You may be able to get something like SendKeys to simulate an Alt-F4 using the windows handle, or if I'm not mistaken, .Net 4.5 has some additional closing routines you could try.

Nonetheless, here is the code to determine which windows are chrome and which of those are incognito. They then "kill", but it doesn't close the window, just kills the browsing (Aw, Snap! as Chrome puts it).

        [DllImport("user32.dll")]
        static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

        [DllImport("user32.dll")]
        static extern bool CloseWindow(IntPtr hWnd);

        [DllImport("user32")]
        private static extern bool SetForegroundWindow(IntPtr hwnd);

        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

        private void button1_Click(object sender, EventArgs e)
        {
            var proc = Process.GetProcesses().OrderBy(x => x.ProcessName);

            foreach (Process prs in proc)
                if (prs.ProcessName == "chrome" && WmiTest(prs.Id))
                {
                    prs.Kill();

                    //To test SendKeys, not working, but gives you the idea
                    //SetForegroundWindow(prs.Handle);
                    //SendKeys.Send("%({F4})");
                }
        }

        private bool WmiTest(int processId)
        {
            using (ManagementObjectSearcher mos = new ManagementObjectSearcher(string.Format("SELECT CommandLine FROM Win32_Process WHERE ProcessId = {0}", processId)))
                foreach (ManagementObject mo in mos.Get())
                    if (mo["CommandLine"].ToString().Contains("--disable-databases"))
                        return true;
            return false;
        }


来源:https://stackoverflow.com/questions/14132142/using-c-sharp-to-close-google-chrome-incognito-windows-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!