怎样防止Delphi程序的重复执行?

wu_yongcai 2000-08-21 04:01:00
...全文
142 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wfmwg 2001-01-11
  • 打赏
  • 举报
回复
先在mainform中声明Hmutex: THandle;
然后在*.dpr 文件中:
Hmutex := CreateMutex(nil, false, '程序名');
if not (waitForSingleObject(hmutex, 0) <> wait_timeout) then
begin
Application.MessageBox('此程序已经运行,不能再次打开!', '警告!', MB_ICONERROR);
halt;
end
else
;;;;;
alin 2000-08-22
  • 打赏
  • 举报
回复
unit un_DoIExist;

interface

uses Windows,SysUtils,Classes;

function DoIExist(WndTitle : String) : Boolean;

implementation

function DoIExist(WndTitle : String) : Boolean;
var
hSem : THandle;
hWndMe :HWnd;
// hWndPrev : HWnd;
semNm,
wTtl : Array[0..256] of Char;
begin

Result := False;

//Initialize arrays
StrPCopy(semNm, WndTitle);
StrPCopy(wTtl, WndTitle);

//Create a Semaphore in memory - If this is the first instance, then
//it should be 0.
hSem := CreateSemaphore(nil, 0, 1, semNm);

//Now, check to see if the semaphore exists
if ((hSem <> 0) AND (GetLastError() = ERROR_ALREADY_EXISTS)) then
begin
CloseHandle(hSem);
//We'll first get the currently executing window's handle then change its title
//so we can look for the other instance
hWndMe := FindWindow(nil, wTtl);
SetWindowText(hWndMe, 'zzzzzzz');
//What we want to do now is search for the other instance of this window
//then bring it to the top of the Z-order stack.
hWndMe := FindWindow(nil, wTtl);
if (hWndMe <> 0) then
begin
if IsIconic(hWndMe) then
ShowWindow(hWndMe, SW_SHOWNORMAL)
else
SetForegroundWindow(hWndMe);
end;
Result := True;
//Could put the Halt here, instead of in the FormCreate method,
//unless you want to do some extra processing.
//Halt;
end;
end;

end.


//在主窗口创建时加入
Self.caption:='数据服务管理';
if DoIExist(Self.Caption) then Halt;

Nicrosoft 2000-08-21
  • 打赏
  • 举报
回复
用API函数FindWindow()找同样的窗口标题,如果返回0则说明没有实例运行,如果返回非0说明有实例已经运行(返回的是它的句柄),则将自己退出。

5,386

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧