using KGIS.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Kingo.Plugin.EngineEditor.Common
{
public class GetAllDesktopWindows
{
private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
//用来遍历所有窗口
[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);
[DllImport("user32.dll", EntryPoint = "IsWindow")]
public static extern bool IsWindow(IntPtr hWnd);
///
/// 自定义一个类,用来保存句柄信息,在遍历的时候,随便也用空上句柄来获取些信息
///
public struct WindowInfo
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
public List ToGetAllDesktopWindows()
{
//用来保存窗口对象 列表
List wndList = new List();
List wndList_IsWindows = new List();
try
{
//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
GetWindowTextW(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);
if (wndList != null && wndList.Count() > 0)
{
for (int u = 0; u < wndList.Count(); u++)
{
if (wndList[u].hWnd != IntPtr.Zero && IsWindow(wndList[u].hWnd) == true)//不为空且是窗口
{
if (string.IsNullOrWhiteSpace(wndList[u].szWindowName) == false)
{
wndList_IsWindows.Add(wndList[u]);
}
else
{
continue;
}
}
else
{
continue;
}
}
}
return wndList_IsWindows;
}
catch (Exception ex)
{
LogAPI.Debug("获取所有窗口句柄时失败,异常原因: " + ex + " ; ");
return null;
}
finally
{
if (wndList != null && wndList.Count() > 0)
{
wndList = null;
}
if (wndList_IsWindows != null && wndList_IsWindows.Count() > 0)
{
wndList_IsWindows = null;
}
}
}
}
}