博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一种常见的禁止多实例运行的方法

Posted on 2008-11-07 09:46  YangHe  阅读(257)  评论(0)    收藏  举报
一种常见的禁止多实例运行的方法
 在DELPHI的工程文件中

program Project1;

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

{$R *.res}

var
  HMutex:Hwnd;
  Ret:Integer;
  Reg :integer;

begin
  Application.Initialize;
  Application.Title :='这是一个防止多个实例运行的程序';
  HMutex  :=CreateMutex(nil,False,Pchar('这是一个防止多个实例运行的程序'));
  Reg :=GetLastError;
  if Reg<>ERROR_ALREADY_EXISTS then
    begin
      Application.CreateForm(TForm1, Form1);
    end
  else
    begin
      MessageBox(0,'实例已经运行了!','错误', MB_OK + MB_ICONERROR);
      ReleaseMutex(hMutex);
    end;
  Application.Run;
end.