另外,该函数不列举子窗口,除了几种拥有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;
责任编辑:虫虫