Home >Backend Development >C++ >How Can I Identify and List All Windows Belonging to a Specific Process Using C#?
Identifying and Enumerating Windows of a Specific Process Using .NET
Finding all windows created by a particular process can be a valuable task for various purposes. Using C#, this can be efficiently achieved by leveraging the EnumThreadWindows function.
To start, obtain the process ID (PID) of the application for which you want to list the windows. Next, call EnumThreadWindows for each thread belonging to the process. This function accepts a callback delegate that takes a window handle as a parameter and returns true if the enumeration should continue. Within this delegate, add the handles to a collection.
Here's the C# code to enumerate all windows belonging to a process:
delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam); static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processId) { var handles = new List<IntPtr>(); foreach (ProcessThread thread in Process.GetProcessById(processId).Threads) EnumThreadWindows(thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero); return handles; }
To demonstrate its usage, here's a sample code that enumerates the explorer process windows and displays their titles:
private const uint WM_GETTEXT = 0x000D; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam); [STAThread] static void Main(string[] args) { foreach (var handle in EnumerateProcessWindowHandles( Process.GetProcessesByName("explorer").First().Id)) { StringBuilder message = new StringBuilder(1000); SendMessage(handle, WM_GETTEXT, message.Capacity, message); Console.WriteLine(message); } }
The above is the detailed content of How Can I Identify and List All Windows Belonging to a Specific Process Using C#?. For more information, please follow other related articles on the PHP Chinese website!