Home > Backend Development > C++ > How to Enumerate Windows of a Specific Process in .NET?

How to Enumerate Windows of a Specific Process in .NET?

Patricia Arquette
Release: 2025-01-05 21:14:48
Original
929 people have browsed it

How to Enumerate Windows of a Specific Process in .NET?

Enumerating Windows of a Specific Process in .NET

Finding all windows created by a specific process is a common requirement in many applications. In .NET, several methods are available to achieve this task. One approach involves enumerating thread windows associated with the target process.

Using the EnumThreadWindows Function

The EnumThreadWindows function from the user32.dll library allows enumeration of all windows belonging to a particular thread. To enumerate windows of a specific process, you can iterate through its threads and invoke EnumThreadWindows for each thread.

Code Implementation:

The following delegate is used as a callback in EnumThreadWindows:

delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);
Copy after login

The following code snippet enumerates the window handles of a process using its process ID (PID):

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

Sample Usage:

To demonstrate the usage, you can retrieve the window titles and print them to the console:

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 to Enumerate Windows of a Specific Process in .NET?. For more information, please follow other related articles on the PHP Chinese website!

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