查找并关闭多个窗口

本文关键字:窗口 查找 | 更新日期: 2023-09-27 18:24:54

下面的代码找到一个以特定"窗口名称"开头的窗口,然后将其关闭。然而,同时打开了多个同名窗口。我需要同时关闭所有这些。我该怎么做?

foreach (Process proc in Process.GetProcesses())
{
    string toClose = null;
    if (proc.MainWindowTitle.StartsWith("untitled"))
    {
        toClose = proc.MainWindowTitle;
        int hwnd = 0;
        //Get a handle for the Application main window
        hwnd = FindWindow(null, toClose);
        //send WM_CLOSE system message
        if (hwnd != 0)
            SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);        
    }
}

查找并关闭多个窗口

您可以使用Process.GetProcessesByName方法,该方法返回Process类型的数组。例如,如果打开了2个无标题实例,它将返回一个由2个进程组成的数组。

有关详细信息,请参阅:http://msdn.microsoft.com/en-us/library/System.Diagnostics.Process.GetProcessesByName.aspx

希望这有帮助:)

编辑:

枚举窗口并按名称查找窗口。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
    class Program
    {
        protected delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        protected static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        protected static extern int GetWindowTextLength(IntPtr hWnd);
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lp1, string lp2);
        [DllImport("user32.dll")]
        protected static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
        [DllImport("user32.dll")]
        protected static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
        private static void Main(string[] args)
        {
            EnumWindows(EnumTheWindows, IntPtr.Zero);
            Console.ReadLine();
        }
        static uint WM_CLOSE = 0x10;
        protected static bool EnumTheWindows(IntPtr hWnd, IntPtr lParam)
        {
            int size = GetWindowTextLength(hWnd);
            if (size++ > 0 && IsWindowVisible(hWnd))
            {
                StringBuilder sb = new StringBuilder(size);
                GetWindowText(hWnd, sb, size);
                if (sb.ToString().StartsWith("Untitled"))
                    SendMessage(hWnd, WM_CLOSE, 0, 0);
            }
            return true;
        }
    }
}