Delphi中保证程序只运行一个实例的方法总结

在做Delphi的一个小工具的时候,要让自己的程序保证只启动一个实例如下有几种方法实现:

1.使用系统函数FindWindows()函数来实现:

program Project1;

uses
  Forms, Windows,//添加Windows单元
  offertool in 'offertool.pas' {foffertool},
  MyThread in 'MyThread.pas',
  offerchild in 'offerchild.pas' {fofferchild};

{$R *.res}

var
  Hwnd:THandle;  //添加一个句柄 

begin
  Hwnd := FindWindow('Tfoffertool',nil);  //参数1:窗口类名,参数2:窗口标题
  if Hwnd=0 then
  begin
    Application.Initialize;
    Application.CreateForm(Tfoffertool, foffertool);
    Application.Run;
  end
  else
  begin
    Application.MessageBox('已经运行了一个实例','提示',MB_OK);
  end;
end.


2.使用使用互斥对象来实现:

program Project1;


uses
  Forms, Windows, //添加Windows单元
  offertool in 'offertool.pas' {foffertool},
  MyThread in 'MyThread.pas',
  offerchild in 'offerchild.pas' {fofferchild};

{$R *.res}

var
  myMutex:THandle; //添加一个互斥锁句柄

begin
  myMutex := CreateMutex(nil,True,'新股代理申购报盘');
  if GetLastError<>ERROR_ALREADY_EXISTS then
  begin
    Application.Initialize;
    Application.CreateForm(Tfoffertool, foffertool);
    Application.Run;
  end
  else
    Application.MessageBox('已经运行了一个实例','提示',MB_OK);
end.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值