歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Delphi中保證程序只運行一個實例的方法總結

Delphi中保證程序只運行一個實例的方法總結

日期:2017/3/1 9:34:35   编辑:Linux編程

在做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.

Copyright © Linux教程網 All Rights Reserved