2013-07-25 55 views
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);   
    } 
} 
+1

你現在的代碼有什麼問題?你在尋找什麼樣的「高效」? –

+0

基本上當前的代碼只會關閉一個叫做「無標題」的窗口,並且會打開其他同名的窗口,它需要一次性關閉它們。 –

+0

是您從無標題運行的窗體,它是第一個形式關閉? – Bit

回答

2

您可以使用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; 
     } 
    } 
} 
+0

抱歉,我的錯最初應該已經解釋得更清楚了,這是在正確的軌道上,但窗戶並不完全說「無標題 - abc」,「無標題 - abg」等。「無標題」等 –

+1

看看EnumWindows http://msdn.microsoft.com/en-us/library/ms633497(v=vs.85).aspx) –

+0

此外我需要通過窗口標題進行搜索。目前的代碼工作正常,但它一次只關閉一個窗口。我需要把它變成一個數組,應該可以做到這一點,但我該如何去做呢? –