您的位置:首页 > 编程语言 > C#

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

2011-08-29 14:24 218 查看
与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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: