如何避免再次运行同一个程序。(100分)

  • 主题发起人 主题发起人 lzlishl
  • 开始时间 开始时间
L

lzlishl

Unregistered / Unconfirmed
GUEST, unregistred user!
如和在程序中控制,避免在同一台机子上运行两次/或,如何在程序中知道它本身已经在运行。
 
给你个例子吧:
var
MutexHandle: THandle; //定义互斥句柄
//防止二次运行

{$R *.res}

begin
// whether existed
MutexHandle := CreateMutex(nil, TRUE, '实时通讯系统客户端');
if MutexHandle <> 0 then
begin
if GetLastError = ERROR_ALREADY_EXISTS then
begin
MessageBox(0, '实时通讯系统客户端已经运行...',
'不好意思', mb_IconHand);
CloseHandle(MutexHandle);
Halt; // 'Halt' Is stop running the actual application.
end;
end;
Application.Initialize;
Application.CreateForm(TfrmClient, frmClient);
if ReadSetting(RegSession,'FormAutoHide','1')='1' then Application.ShowMainForm :=False;
Application.Run;
end.
 
CreateMutex(nil, false, 'IeDog');
if GetLastError = ERROR_ALREADY_EXISTS then //if it failed then there is another instance
begin
SendMessage(HWND_BROADCAST,RegisterWindowMessage('IeDog'),0,0);
Halt(0);//Lets quit
end;

Application.Initialize;
Application.Title := 'IeDog';
Application.CreateForm(Tmainfrm, mainfrm);
Application.Run;
 
xxhadsg的例子有个小问题,请修改一句:

begin
// whether existed
MutexHandle := CreateMutex(nil, TRUE, '实时通讯系统客户端');
if MutexHandle <> 0 then
begin
if GetLastError = ERROR_ALREADY_EXISTS then
begin
MessageBox(0, '实时通讯系统客户端已经运行...',
'不好意思', mb_IconHand);
CloseHandle(MutexHandle);
//Halt; // 'Halt' Is stop running the actual application.
exit;//将上面这一句改成exit会比较好,因为halt不会释放内存,包括Delphi在begin..end之间自动编译的内存分配也不会被halt释放,因为halt后程序就立刻消亡了。
end;
end;
Application.Initialize;
Application.CreateForm(TfrmClient, frmClient);
if ReadSetting(RegSession,'FormAutoHide','1')='1' then Application.ShowMainForm :=False;
Application.Run;
end.


 
防止多个应用程序的实例,并且第二个实例会激活第一个实例
program Project1;

uses
Forms,
Windows,
Messages,
Unit1 in 'Unit1.pas' {Form1};

{$R *.res}

var
hMutex,hApp:HWND;
begin
Application.Initialize;
//建立互斥对象
hMutex:=CreateMutex(nil,False,PChar(SAppName));
If GetLastError=ERROR_ALREADY_EXISTS Then
begin
//已经运行,找到句柄
hApp:=FindWindow('TApplication',PChar(SAppName));
//激活
if IsIconic(hApp) then
PostMessage(hApp,WM_SYSCOMMAND,SC_RESTORE,0);
SetForegroundWindow(hApp);
//释放互斥对象
ReleaseMutex(hMutex);
Application.Terminate;
Exit;
end;
Application.CreateForm(TForm1, Form1);
Application.Run;
//释放互斥对象
ReleaseMutex(hMutex);
end.
 
谢谢各位,尤其是zqw0117,ysai的热心,今后一定向各位认真讨教。
 
呵呵,多说一句,ysai的例子也应该稍稍修改一下,由于ReleaseMutex函数针对的是多线程
互斥对象的释放,而楼主的要求只是防止单进程多次调用,因此,应该将ysai例子中的
ReleaseMutex函数调用改为:CloseHandle(hMutex);
 
后退
顶部