以下是用delphi的一个空project做的测试(完整的代码):
program Project1;
uses
Windows, ///该unit一定要包含,系统用到了windows api
Forms,
Unit1 in 'Unit1.pas' {Form1};
var
myMutex,hMutex,FindHid:HWND;
MoudleName:string;
function EnumWndProc(hwnd:Thandle;param:Cardinal):boolean;stdcall;
//由于用于api回调函数,请使用windows传统的参数传递方式stdcall
var
ClassName,WinMoudleName:string;
WinInstance:THandle;
begin
result:=true;
SetLength(ClassName,100);
GetClassName(hwnd,pchar(ClassName),length(ClassName));//获得当前遍历窗口的类名
ClassName:=pchar(ClassName);//在字符串后加结束符,确定字符串结束
if ClassName=TForm1.ClassName then//比较
begin
WinInstance:=GetWindowLong(hwnd,GWL_HINSTANCE);//获得当前遍历窗口的实例
setlength(WinMoudleName,100);
GetModuleFileName(WinInstance,pchar(WinMoudleName),length(WinMoudleName));
//获得当前遍历窗口的程序文件名
WinMoudleName:=pchar(WinMoudleName);
if WinMoudleName=MoudleName then//MoudleName为工程全局变量,自身程序的文件名
begin
FindHid:=hwnd;//FindHid为工程全局变量保存找到的句炳
result:=false;//找到以后就结束遍历
end;
end;
end;
{$R *.res}
begin
hMutex:=CreateMutex(nil,false,'Project1');
if WaitForSingleObject(hMutex,0)<>wait_TimeOut then
begin
myMutex:=CreateMutex(nil,false,'Project1');// CreateMutex建立互斥对象,并且给互斥对象起一个唯一的名字。
if WaitForSingleObject(myMutex,0)<>wait_TimeOut then//程序没有被运行过
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
End;
end
else
begin
SetLength(MoudleName,100);
GetModuleFileName(HInstance,pchar(MoudleName),length(MoudleName));
//获得自己程序文件名
MoudleName:=pchar(MoudleName);
EnumWindows(@EnumWndProc,0);//调用枚举函数
if FindHid<>0 then
SetForegroundWindow(FindHid);
end;
end.
可参考: http://www.7880.com/Info/Article-215ddec0.html