0

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

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);        
    }
}
4

1 回答 1

2

您可以使用返回 Process 类型数组的 Process.GetProcessesByName 方法。例如,如果您打开了 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;
        }
    }
}
于 2013-07-25T21:02:55.113 回答