.NET Compact Framework 2.0下调用EnumWindows(Callback方式)

本文介绍如何利用.NETCF2.0中的Callback特性,通过调用EnumWindows API函数来遍历所有窗口,并获取每个窗口的标题。示例代码在VS.NET2005下已验证通过。

上个月发过一篇文章是.net cf 1.x实现EnumWindows,因为.net cf 1.x不支持Callback方式,所以实现起来比较繁琐,而且效率不高。.net cf 2.0中就不同了,已经加入了的对Callback的支持了,所以我们就可以调用EnumWindows这个API函数来遍历所有的窗口了,下面是我写的一个Demo:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace EnumWindows
{
    public partial class Form1 : Form
    {
        public delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

        EnumWindowsProc callbackDelegate;
        IntPtr callbackDelegatePointer;

        [DllImport("coredll.dll", SetLastError = true)]
        public static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);
        [DllImport("coredll.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int GetWindowTextLength(IntPtr hWnd);
        [DllImport("coredll.dll")]
        public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
        public Form1()
        {
            InitializeComponent();

            callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
            callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);

            EnumWindows(callbackDelegatePointer, 0);


        }

        public int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
        {
            int length = GetWindowTextLength(hwnd);
            StringBuilder sb = new StringBuilder(length + 1);
            GetWindowText(hwnd, sb, sb.Capacity);
            System.Diagnostics.Debug.WriteLine("Window: " + hwnd.ToString() + "," + sb.ToString());

            return 1;
        }
    }

}
vs.net 2005 下调试通过!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值