C#用API如何遍历所有窗口句柄
时间:2010-12-15 来源:陈同学
//用来遍历所有窗口
[DllImport("user32.dll")]
private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
//获取窗口Text
[DllImport("user32.dll")]
private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
//获取窗口类名
[DllImport("user32.dll")]
private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
public struct WindowInfo //自定义一个类,用来保存句柄信息,有遍历的时候,随便也用空上句柄来获取些信息,呵呵
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
public WindowInfo[] GetAllDesktopWindows()
{
List<WindowInfo> wndList = new List<WindowInfo>();
//enum all desktop windows
EnumWindows(delegate(IntPtr hWnd, int lParam)
{
WindowInfo wnd = new WindowInfo();
StringBuilder sb = new StringBuilder(256);
//get hwnd
wnd.hWnd = hWnd;
//get window name
(hWnd, sb, sb.Capacity);
wnd.szWindowName = sb.ToString();
//get window class
GetClassNameW(hWnd, sb, sb.Capacity);
wnd.szClassName = sb.ToString();
//add it into list
wndList.Add(wnd);
return true;
}, 0);
return wndList.ToArray();
}