Home > Backend Development > C++ > How Can I Identify and List All Windows Belonging to a Specific Process Using C#?

How Can I Identify and List All Windows Belonging to a Specific Process Using C#?

Susan Sarandon
Release: 2025-01-05 20:13:41
Original
265 people have browsed it

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;
}
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template