Delphi 代码:
//----------------------------------------------------------------------------
var
hMutex:hwnd;
ret:integer;
begin
Application.Initialize;
hmutex:=createMutex(nil,false,'MyAPP');
ret:=getlasterror;
if ret <>error_already_exists then
begin
Application.CreateForm(TMainFrm, MainFrm);
Application.Run;
end
else
begin
Application.MessageBox('program已经运行,请不要运行两次','program不能运行',MB_搞定 or MB_ICONERROR);
end;
releasemutex(hmutex);
end.
//----------------------------------------------------------------------------
二、通过查找系统原子表的方法来判断:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USERES("Project1.res");
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
const char *Atom = "SingleApp";
try
{
if (GlobalFindAtom(Atom) != 0)//在系统原子表中找原子
{
::MessageBox(NULL,"已经运行了一个实例!",Application->Title.c_str(),MB_OK|MB_SYSTEMMODAL);
return 0;
}
GlobalAddAtom(Atom);//增加原子
Application->Initialize();
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
GlobalDeleteAtom(GlobalFindAtom(Atom));//删除原子
return 0;
}
//---------------------------------------------------------------------------
三、通过FindWindow函数来判断:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USERES("Project1.res");
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
HWND hdc = FindWindow("TForm1","Form1");
if (NULL != hdc)
{
::MessageBox(NULL,"已经运行了一个实例!",Application->Title.c_str(),MB_OK|MB_SYSTEMMODAL);
return 0;
}
Application->Initialize();
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}
//---------------------------------------------------------------------------