Comment énumérer toutes les fenêtres appartenant à un processus particulier en utilisant .NET?

Comment puis-je trouver toutes les fenêtres créées par un processus particulier en utilisant c #?

METTRE À JOUR

J’ai besoin d’énumérer toutes les fenêtres appartenant à un processus particulier en utilisant le PID (identifiant de processus) d’une application.

Utilisez le EnumWindows API Win32 (si vous voulez des fenêtres enfant EnumChildWindows )) ou vous pouvez utiliser EnumThreadWindows .

[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData); 

Ensuite, vérifiez à quel processus appartient chaque fenêtre en utilisant l’API Win32 GetWindowThreadProcessId

 [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId); 
 delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam); static IEnumerable EnumerateProcessWindowHandles(int processId) { var handles = new List(); foreach (ProcessThread thread in Process.GetProcessById(processId).Threads) EnumThreadWindows(thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero); return handles; } 

et exemple d’utilisation:

 private const uint WM_GETTEXT = 0x000D; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, SsortingngBuilder lParam); [STAThread] static void Main(ssortingng[] args) { foreach (var handle in EnumerateProcessWindowHandles( Process.GetProcessesByName("explorer").First().Id)) { SsortingngBuilder message = new SsortingngBuilder(1000); SendMessage(handle, WM_GETTEXT, message.Capacity, message); Console.WriteLine(message); } } 

Un ancien thread, mais ça m’a fait démarrer alors voici une petite fonction utilitaire qui trouvera une fenêtre enfant correspondant à un lambda (prédicat). Soyez facile à changer pour retourner une liste. Plusieurs critères sont traités dans le prédicat.

  public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam); [DllImport("user32.Dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam); ///  /// Find a child window that matches a set of conditions specified as a Predicate that receives hWnd. Returns IntPtr.Zero /// if the target window not found. Typical search criteria would be some combination of window atsortingbutes such as /// ClassName, Title, etc., all of which can be obtained using API functions you will find on pinvoke.net ///  ///  /// Example: Find a window with specific title (use Regex.IsMatch for more sophisticated search) ///  Win32.GetWindowText(ptr) == "Dashboard");]]> ///  /// Handle to window at the start of the chain. Passing IntPtr.Zero gives you the top level /// window for the current process. To get windows for other processes, do something similar for the FindWindow /// API. /// Predicate that takes an hWnd as an IntPtr parameter, and returns True if the window matches. The /// first match is returned, and no further windows are scanned. ///  hWnd of the first found window, or IntPtr.Zero on failure  public static IntPtr FindWindow(IntPtr parentHandle, Predicate target) { var result = IntPtr.Zero; if (parentHandle == IntPtr.Zero) parentHandle = Process.GetCurrentProcess().MainWindowHandle; EnumChildWindows(parentHandle, (hwnd, param) => { if (target(hwnd)) { result = hwnd; return false; } return true; }, IntPtr.Zero); return result; } 

Exemple

 var foundHandle = Win32.FindWindow(IntPtr.Zero, ptr => Win32.GetWindowText(ptr) == "Dashboard"); 

Au bout d’un moment, j’ai trouvé un moyen simple et plus court:

Vous aurez besoin de: ” utiliser System.Diagnostics;

  [DllImport("kernel32.dll", SetLastError = true)] // Optional [return: MarshalAs(UnmanagedType.Bool)] // Optional private void button1_Click(object sender, EventArgs e) { AllocConsole(); // Easy to read // Optional Process[] processlist = Process.GetProcesses(); foreach (Process process in processlist) { if (!ssortingng.IsNullOrEmpty(process.MainWindowTitle)) { Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle); } } }