一个程序同时只能运行一个(50分)

  • 主题发起人 newdelphiboy
  • 开始时间
N

newdelphiboy

Unregistered / Unconfirmed
GUEST, unregistred user!
我知道防止一个程序同时运行多次可以采用内核对象互斥区(Mutex)来判断.但现在问题是
我写了这一个程序,带有一个启动页面.所以不论我现在是在主页面用Mutex来判断,还是在
启动页面来判断,第二次运行的该程序的启动页面总是要出现,然后才关闭.
我想问怎么才能做到如果是同时第二次运行这程序,怎么才能不出现启动页面,而是判断出
已经有一个程序后就自动关闭呢.
 
在程序入口处写
program Project1;

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

{$R *.res}

begin
//加在这里
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
 
将判断放到启动页面show之前不行吗
 
你查一下以前的贴子吧很多
 
var
hMutex:HWND;
Ret:Integer;
begin
Application.Title := '你的名称';
hMutex:=CreateMutex(nil,False,'你的名称');
Ret:=GetLastError;
If Ret<>ERROR_ALREADY_EXISTS Then
Begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end
 
还要加上
ReleaseMutex(hMutex)
 
用FINDWINDOW来判断一下,你的程序是不是打开,如此而已
我是怎么实现的
高级的不大懂
 
给你一个例子
program menjin;

uses
Forms,
windows,
main in 'main.pas' {frmmain},

{$R *.RES}

var
hMutex: THandle;

begin
hMutex := CreateMutex(nil, False, 'menjin');
if WaitForSingleObject(hMutex, 0) = wait_TimeOut then
begin
MessageBox(Handle, '本程序已运行','警告!', MB_OK);
Exit;
end;
Application.Initialize;
Application.CreateForm(Tfrmmain, frmmain);
Application.Run;
end
 
方法多去了,自己用上面的全文搜索查
 
只运行一次的话不用互斥的,用事件就好了,其实都一样
OpenEvent,OpenMutex,CreateEvent,CreateMutex
const
_EventName='_Your_Enent_Name';
begin
if OpenEvent(EVENT_ALL_ACCESS,False,PChar(_EventName)<>0 then
Exit
else
CreateEvent();//创建Event
Application.Initlize;
 
在初始化时,用FINDWINDOW函数找你的程序句柄,找到了就不启动即可!!
 
查找窗口的标题,如发现与现有窗口标题相同的窗口则程序自动关闭
具体的代码应该加在项目文件Project里面:
program Project1;

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

{$R *.res}

begin
//...代码
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
 
接受答案了.
 
顶部