首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

怎么防止同一目录下的EXE文件执行两次

2013-07-01 
如何防止同一目录下的EXE文件执行两次如题:在不同的目录下有相同的EXE文件,想在代码中进行控制,同一个文件

如何防止同一目录下的EXE文件执行两次
如题:

在不同的目录下有相同的EXE文件,想在代码中进行控制,同一个文件夹上的这个EXE文件只能被执行一次,第二次执行的时候进行提示并退出,但不同文件下运行相同的EXE文件是被允许的,请教各位,这种如何实现? 重复执行
[解决办法]
program Project1;

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

{$R *.RES}

begin
  Application.Initialize;

  Application.Title:='我的测试程序';
  CreateMutex(nil,False,'我的测试程序');
    if   (GetLastError()=ERROR_ALREADY_EXISTS)  then
     begin
       Application.MessageBox(PChar('当前程序只能且只有一个实例运行'), '错误信息:', MB_ICONERROR);
       exit;
     end;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.


楼主将分 分给我吧
[解决办法]
program Project1;

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

{$R *.res}

var
  hMutex: HWND;
  lpName: String;

begin
  lpName := StringReplace(ParamStr(0), '\', '#', [rfReplaceAll]);
  hMutex := OpenMutex(MUTEX_ALL_ACCESS, False, PChar(lpName));
  if hMutex = 0 then
  begin
    hMutex := CreateMutex(nil, False, PChar(lpName));
    Application.Initialize;
    Application.CreateForm(TForm1, Form1);
  Application.Run;
    ReleaseMutex(hMutex);
  end;
end.


这才是答案。

热点排行