C#调用API函数EnumWindows枚举窗口的方法

原文 http://blog.csdn.net/dengta_snowwhite/article/details/6067928

与C++不同,C#调用API函数需要引入.dll文件,步骤如下:

 

1. 添加命名空间

using System.Runtime.InteropServices;

 

2. DllImport调入EnumWindows等函数

        [DllImport("user32.dll")]

        //EnumWindows函数,EnumWindowsProc 为处理函数

        private static extern int EnumWindows(EnumWindowsProc ewp, int lParam);       

        其他常用函数格式如下:
        [DllImport("user32.dll")]
        private static extern int GetWindowText(int hWnd, StringBuilder title, int size);
        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(int hWnd);
        [DllImport("user32.dll")]
        private static extern int GetWindowTextLength(int hWnd);
        [DllImport("USER32.DLL")]
        private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
        [DllImport("USER32.DLL")]
        private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

 

3. 申明委托

public delegate bool EnumWindowsProc(int hWnd, int lParam);

 

4.定义委托函数,ADA_EnumWindowsProc为执行函数,返回true则EnumWindows继续枚举下一个顶级窗口直到枚举完

        EnumWindowsProc ewp = new EnumWindowsProc(ADA_EnumWindowsProc);
        EnumWindows(ewp, 0);

 

5. 实现委托函数

        public bool  ADA_EnumWindowsProc(int hWnd, int lParam)
        {
            int cTxtLen, i;
            String cTitle, strtmp;
            if (IsWindowVisible(hWnd)) 
            {

//..........对每一个枚举窗口的处理
                //Get the task name
                cTxtLen = GetWindowTextLength(hWnd) +1;
                StringBuilder text = new StringBuilder(cTxtLen);
                GetWindowText(hWnd, text, cTxtLen);
                cTitle = text.ToString();
                cTitle = cTitle.ToUpper();

//...............
            }

            return true;
        }

你可能感兴趣的:(windows)