簡體   English   中英

查找並關閉多個Windows

[英]Find and close multiple Windows

我下面的代碼找到一個窗口,以特定的“窗口名稱”開頭,然后關閉它。 但是,同時打開多個具有相同名稱的窗口。 我需要同時關閉所有這些。 我該怎么做呢?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM