-
-
-
编辑:xujie 时间:2007-11-27 来源:淘学考试网 推荐好友
|
函数形式:
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, //callback function
LPARAM lParam); //application-defined value
其中 WNDENUMPROC 是回调函数,回调函数中写自己想做的*作,当调用EnumWindows的时候,每次遇到一个窗口,系统就调用一次你的WNDENUMPROC ,然后把窗口句柄传给你。
EnumWindows
函数成功则返回非0值;
函数失败则返回0值;
EnumWindowsProc 返回0值,同样导致函数EnumWindows 返回0值。
另外,该函数不列举子窗口,除了几种拥有WS_CHILD 风格的系统所属窗口。
MSDN:
The EnumWindows function does not enumerate child windows,with the exception of a few top-level windows owned by the system that have the WS_CHILD style.
使用举例:
先声明一个EnumWindowsProc ,比如:
BOOL CALLBACK EnumWindowsProc_1(HWND hwnd,LPARAM lparam) ;
然后实现此函数,写入自己想做的事情,比如:
BOOL CALLBACK EnumWindowsProc_1(HWND hwnd,LPARAM lparam)
{ char lpWinTitle[256];
::GetWindowText(hwnd,lpWinTitle,256-1);
CString m_strTitle;
m_strTitle.Format("%s",lpWinTitle);
if(m_strTitle.Find("Internet Explorer")!=-1)
{ AfxMessageBox("这是一个IE窗口!") ; }
return TRUE ;
}
然后就可以在其他地方调用EnumWindows的时候使用回调函数,比如:
::EnumWindows(EnumWindowsProc_1,0) ;
这样每当遇到IE窗口时,就会进行 提示“这是一个IE窗口!” 的*作。
方法二:
不用互斥对象。
我们可以利用向系统添加全局原子的方法,来防止多个程序实例的运行。全局原子由Windows 系统负责维持,它能保证其中的每个原子都是唯一的,管理其引用计数,并且当该全局原子的引用计数为0时,从内存中清除。我们用GlobalAddAtom 函数向全局原子添加一个255个字节以内的字符串,用GlobalFindAtom来检查是否已经存在该全局原子,最后在程序结束时用GlobalDeleteAtom函数删除添加的全局原子。示例如下:
Uses Windows
const iAtom=‘SingleApp’;
begin
if GlobalFindAtom(iAtom)=0 then
begin
GlobalAddAtom(iAtom);
Application.Initialize;
Application.CreateForm(TForm1,Form1);
Application.Run;
GlobalDeleteAtom(GlobalFindAtom(iAtom));
end
else
MessageBox(0,‘You can not run a second copy of this App’,‘’,mb_OK);
end.
利用全局原子的引用计数规则,我们还可以判断当前共运行了该程序的多少个实例:
var i:Integer;
begin
I:=0;
while GlobalFindAtom(iAtom)<>0 do
begin
GlobalDeleteAtom(GlobalFindAtom(iAtom));
i:=i+1;
end;
ShowMessage(IntToStr(I));
end;
baidu
|