begin
hMutex := CreateMutex(nil, True, 'main');
try
if not (ERROR_ALREADY_EXISTS = GetLastError()) then
begin
Application.Initialize;
Application.Title := 'main';
Application.CreateForm(TfrmMain, frmMain);
Application.Run;
end
else
begin
Application.MessageBox('main 已经在运行中!',PChar(Application.Title), MB_OK + MB_ICONERROR);
end;
finally
ReleaseMutex(hMutex);
end;
end.
procedure TForm1.Button2Click(Sender: TObject);
Function IsRun( ProcName:string ):Boolean
var
hSnapshot: THandle;
lppe: TProcessEntry32;
Found: Boolean;
begin
Result:=True;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
lppe.dwSize := SizeOf(TProcessEntry32);
Found := Process32First(hSnapshot, lppe);
while Found do
begin
if ((UpperCase(ExtractFileName(lppe.szExeFile))=UpperCase(ProcName)) or (UpperCase(lppe.szExeFile )=UpperCase(ProcName))) then
begin
Result:=True;
end
Found := Process32Next(hSnapshot, lppe);
end;
end;
if Not IsRun( 'main.exe' ) then
begin
WinExec('C:\main.exe',SW_SHOWNORMAL);
end;
end;
在(dpr)工程文件里编写如下代码:
var
hMutex: THandle;
begin
hMutex := CreateMutex(nil, True, 'main');
try
if not (ERROR_ALREADY_EXISTS <> GetLastError()) then
begin
Application.MessageBox('main 已经在运行中!',
PChar(Application.Title), MB_OK + MB_ICONERROR);
end;
finally
ReleaseMutex(hMutex);
end;
end.
var
hSnapshot: THandle;
lppe: TProcessEntry32;
Found: Boolean;
begin
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
lppe.dwSize := SizeOf(TProcessEntry32);
Found := Process32First(hSnapshot, lppe);
while Found do
begin
if ((UpperCase(ExtractFileName(lppe.szExeFile))=UpperCase('main.exe')) or (UpperCase(lppe.szExeFile )=UpperCase('main.exe'))) then
begin
//
showmessage('程序正在运行');
end;
Found := Process32Next(hSnapshot, lppe);
end;
end;