关于程序的进程问题。(20分)

  • 主题发起人 主题发起人 hyzzhxia
  • 开始时间 开始时间
H

hyzzhxia

Unregistered / Unconfirmed
GUEST, unregistred user!
我的程序已经都写好了,但是运行时,在单击图标,程序又可以被打开。我如何检测是否有一个同样的程序进程已经在运行了?而自动关闭再次打开的程序?
 
在.dpr文件中写,举例:

program IETool;

uses
Forms,
Windows,
Main in 'Main.pas' {frmMain};

var
hMutex:hwnd;
ret:integer;

{$R *.res}

begin
Application.Initialize;
// run only once---------------------------------------
hMutex:=CreateMutex(nil,false,'project1');
ret:=GetLastError;
if ret=ERROR_ALREADY_EXISTS then
begin
ReleaseMutex(hMutex);
MessageBox(Application.Handle,'抱歉,本程序已经在运行!','收藏伴侣' ,
MB_OK + MB_DEFBUTTON1 + MB_ICONEXCLAMATION);
exit;
end;
//-----------------------------------------------------
Application.CreateForm(TfrmMain, frmMain);
Application.ShowMainForm := false; //Hide Main form, IE toolvar version.
Application.Run;
end.
 
以前的帖子很多了,自己查一下嘛
下次记得先找,别浪费了分
 
用互斥
Var
hMutex:HWND;
Ret:Integer;
begin
Application.Initialize;
Application.Title := 'aaaaaa';
hMutex:=CreateMutex(nil,False,'aaaaaa');
Ret:=GetLastError;
If Ret<>ERROR_ALREADY_EXISTS Then
Begin
Application.CreateForm(TForm1, Form1);
Application.Run;
End
Else
Application.MessageBox('Run Twice!','Notes!',MB_OK);
ReleaseMutex(hMutex);
end.
 
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
mHandle: THandle;
// 保存Mutex句柄
PreviousInstanceWindow:HWND;
Project: string;
AppName:string;

implementation

{$R *.DFM}
initialization
Project := 'RunOnlyOnce_MyProject';
//此处定义自己的项目名称,作为要创建的互斥区名,最好有自己特点已防止重复
mHandle := CreateMutex(nil, True, PChar(Project));
// lpMutexAttributes设为nil,bInitialOwner设为True(即本程序拥有该互斥区)
if GetLastError = ERROR_ALREADY_EXISTS then
//该互斥区已存在则表明已有本程序的另一个实例在运行
begin
showmessage('已经有该程序的一个实例在运行');
AppName:=Application.Title;
//保存程序标题
Application.ShowMainForm := false;
//不显示本窗口
Application.Title := 'destroy me';
//改变程序标题,以使FindWindow找到的是前一个实例窗口
PreviousInstanceWindow := FindWindow(nil,pchar(AppName));
//寻找前一个实例窗口句柄
if PreviousInstanceWindow <> 0 then
//已经找到
if IsIconic(PreviousInstanceWindow) then
//如该窗口最小化则恢复
ShowWindow(PreviousInstanceWindow,SW_RESTORE)
else
SetForegroundWindow(PreviousInstanceWindow);
//否则如程序在后台则将其放到前台
Application.Terminate;
//中止本实例
end;

finalization
if mHandle <> 0 then
//该互斥区对象仍存在则关闭对象
CloseHandle(mHandle);
end.
 
多人接受答案了。
 
后退
顶部