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

How to Enumerate All Windows Belonging to a Specific Process in .NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 19:00:40888browse

How to Enumerate All Windows Belonging to a Specific Process in .NET?

How to enumerate all windows belonging to a specific process in .NET

To enumerate all windows created by a specific process, you can use the following method. First, get the process ID of a specific process. You can then call the EnumerateProcessWindowHandles method in the following code to enumerate all window handles belonging to the 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;
}

The following example will print the titles of all windows belonging to the process named "explorer":

const uint WM_GETTEXT = 0x000D;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, 
    StringBuilder lParam);

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

Statement:
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