刚刚从老旧的VB6.0转移到C#的IDE当中,那玩意简直是干啥啥不行啊,关键Windows10还不支持。。。
最近遇到个小项目(瞎折腾),需要枚举窗口句柄,并且获得相关的信息,各种折腾我,最后一通宵搞定,希望能帮助到需要的人
[C#] 纯文本查看 复制代码
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowTextW(int hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetClassNameW(int hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
public delegate bool WNDENUMPROC(int hWnd, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
/// <summary>
/// 枚举结构
/// </summary>
public struct WindowInfo
{
public int PW_Hwnd;
public string PW_WindowName;
public string PW_ClassName;
}
/// <summary>
/// 枚举当前系统窗口
/// </summary>
/// <returns></returns>
public static WindowInfo[] FindWindows()
{
try
{
List<WindowInfo> WindowsList = new List<WindowInfo>();
EnumWindows(delegate (int APP_Hwnd, int lParam)
{
WindowInfo _W = new WindowInfo();
StringBuilder sb = new StringBuilder(256);
_W.PW_Hwnd = APP_Hwnd;
GetWindowTextW(APP_Hwnd, sb, sb.Capacity);
_W.PW_WindowName = sb.ToString();
GetClassNameW(APP_Hwnd, sb, sb.Capacity);
_W.PW_ClassName = sb.ToString();
WindowsList.Add(_W);
return true;
}, 0);
return WindowsList.ToArray();
}
catch (Exception ex)
{
//处理异常
}
} |