-- 作者:卷积内核
-- 发布时间:8/29/2009 11:15:00 AM
-- C#中获取窗口句柄的方法 及 遍历所有窗口句柄
C#可调用API接口来获取窗口句柄,代码如下 using System; using System.Runtime.InteropServices; namespace tstfindwindow { /// <summary> /// Class1 的摘要说明。 /// </summary> class Class1 { [DllImport( "User32.dll ")] public static extern System.IntPtr FindWindowEx( System.IntPtr parent , System.IntPtr childe , string strclass ,string strname ); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { // // TODO: 在此处添加代码以启动应用程序 // IntPtr p=FindWindowEx(System.IntPtr.Zero,System.IntPtr.Zero,null,"窗口标题"); } } 遍历所有窗口句柄 using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; class CSharpAPIsDemo { private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam); [DllImport("user32.dll")] private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam); //[DllImport("user32.dll")] //private static extern IntPtr FindWindowW(string lpClassName, string lpWindowName); [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 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); return wndList.ToArray(); } }
|