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 に答える