如何防止一个程序执行两次
这是一个比较简单的防止程序执行两次的方法 implementation var hnd: THandle; initialization hnd := CreateMutex(nil, True, 'irgendwaseinmaliges'); if GetLastError = ERROR_ALREADY_EXISTS then Halt; finalization if hnd <> 0 then CloseHandle(hnd); end.
试试吧^_^
这是一个比较简单的防止程序执行两次的方法 implementation var hnd: THandle; initialization hnd := CreateMutex(nil, True, 'irgendwaseinmaliges'); if GetLastError = ERROR_ALREADY_EXISTS then Halt; finalization if hnd <> 0 then CloseHandle(hnd); end.
试试吧^_^
在某些情况下,我们编写的应用程序同时只能有一个实例在内存中运行,例如服务器程序、需要独占某设备的程序,甚至我们仅仅是让程序同时只有一个实例运行(如UltraEdit就是这样做的,让你不能同时运行多个UltraEdit)。要实现此功能,需要在程序中加一点判断的代码,在Windows 95或Win32环境下的Delphi版本中实现的程序如下:
按Ctrl+F12键,选择Project1,加入下列语句
program Project1;uses
windows, {加入该句才能调用函数}
Forms,
Unit1 in 'Unit1.pas'{Form1};{$R *.RES}
const classname='TForm1'; {声明为主窗体的类名}
var handle:integer; {变量}begin
{-----------------主要为该判断部分----------------------}
handle:=findwindow(classname,nil);{查找是否有此类的窗体}
if handle<>0 then {不为0则程序已运行}
begin
messagebox(0,'该程序已经有一个在运行中!','运行',0);{提示程序已运行}
halt; {退出程序}
end;
{------------------------------------------------------}
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
该程序在测试时由于Delphi也生成了此类实例窗体,所以会出现提示框,只有关闭Delphi后单独运行程序才能实现
我运行时出现
[Error] KQ.dpr(55): Undeclared identifier: 'messagebox'
[Error] KQ.dpr(51): Undeclared identifier: 'findwindow'
const classname2='TFrmMain'; {声明为主窗体的类名}
var handle1,handle2:integer; {变量}
begin
{-----------------主要为该判断部分----------------------}
handle1:=findwindow(classname1,nil);{查找是否有此类的窗体}
handle2:=findwindow(classname2,nil);{查找是否有此类的窗体}
if (handle1<>0) or (handle2<>0) then {不为0则程序已运行}
begin
Application.MessageBox('该系统已经在运行中!','通用考勤管理系统',Mb_OK+Mb_IconStop);{提示程序已运行}
halt; {退出程序}
end;
{------------------------------------------------------} Application.Initialize;
为什么一启动就出错