c# 枚举windows当前的所有窗口及子窗口
时间: 2024-03-25 09:39:34 浏览: 24
你可以使用 Windows API 中的 EnumWindows 和 EnumChildWindows 函数来枚举所有窗口及其子窗口。以下是一个 C# 示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
class Program
{
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool IsWindowVisible(IntPtr hWnd);
static void Main(string[] args)
{
List<IntPtr> windows = new List<IntPtr>();
EnumWindows(delegate(IntPtr hWnd, IntPtr lParam)
{
if (IsWindowVisible(hWnd))
{
windows.Add(hWnd);
EnumChildWindows(hWnd, delegate(IntPtr hWndChild, IntPtr lParamChild)
{
if (IsWindowVisible(hWndChild))
{
windows.Add(hWndChild);
}
return true;
}, IntPtr.Zero);
}
return true;
}, IntPtr.Zero);
foreach (IntPtr hWnd in windows)
{
int length = GetWindowTextLength(hWnd);
if (length > 0)
{
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
Console.WriteLine("Window title: " + sb.ToString());
}
}
}
}
```
这个示例代码使用 EnumWindows 函数枚举所有顶级窗口,然后使用 EnumChildWindows 函数枚举每个顶级窗口的子窗口。然后,它使用 GetWindowText 函数获取每个窗口的标题,并将其输出到控制台。你可以根据需要修改代码以执行其他操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)