通过标题模糊查找窗体并关闭窗口

       public static void CloseWindow(string title)
        {
            const int WM_CLOSE = 0x0010;
            IntPtr hWnd = FindWindow(title);
            if (hWnd != IntPtr.Zero)
            {
                SendMessage(hWnd, WM_CLOSE, 0, 0);
            }
        }
        //根据窗体标题查找窗口句柄(支持模糊匹配)
        public static IntPtr FindWindow(string title)
        {
            Process[] ps = Process.GetProcesses();
            foreach (Process p in ps)
            {
                if (p.MainWindowTitle.IndexOf(title) != -1)
                {
                    return p.MainWindowHandle;
                }
            }
            return IntPtr.Zero;
        }
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

 如果是放在循环里,1s执行一次,上面的代码坏处是耗费CPU过高,在本人的机器上大约是1%-6%,本着能省则省的原则,如果知道进程的名字,耗费cpu可以更低

public static void CloseWindow(string title)
        {
           const int WM_CLOSE = 0x0010;
             IntPtr hWnd = FindWindow(title);
             if (hWnd != IntPtr.Zero)
             {
                 SendMessage(hWnd, WM_CLOSE, 0, 0);
             }
             Thread.Sleep(1000);
           
        }

        public static IntPtr FindWindow(string title)
        {
            var ps = Process.GetProcessesByName("ProcessName");
            if (ps.Length>0&&ps[0].MainWindowTitle.IndexOf(title) != -1)
            {
                return ps[0].MainWindowHandle;
            }
            return IntPtr.Zero;
        }
原文地址:https://www.cnblogs.com/haorui/p/3685846.html