C#用API如何遍历所有窗口句柄

1.首先需要声明一个委托函数用于 Win32 API - EnumWindows 的回调函数:

private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam); //IntPtr hWnd用int也可以

2.然后利用 C# 中的平台调用声明从 USER32.DLL 库中调用 API - EnumWindows,具体参数请参考 MSDN - Win32 API。

[DllImport("user32.dll")]

private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);

3.最后实例化委托,调用 EnumWindows。

EnumWindows(delegate(IntPtr hWnd, int lParam) {……},0);

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); 

//自定义一个类,用来保存句柄信息,在遍历的时候,随便也用空上句柄来获取些信息,呵呵 
        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(); 
        }

转载于:https://www.cnblogs.com/chencidi/archive/2010/12/15/1907377.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值