如何保证我的程序同时只能运行一个在内存中?(25分)

  • 主题发起人 主题发起人 mynlxx
  • 开始时间 开始时间
M

mynlxx

Unregistered / Unconfirmed
GUEST, unregistred user!
我现在已经在主窗体的CreatParams里指定WinClassName :='...",,然后运行时判断是否
已经运行,,但由于启动时运行太快,而导致辞主窗体还没创建的时候就运行了两个,该
如何解决?是否有别的方法?如是否可以运行的时候锁定主执行程序,而不能再运行?
 
用互斥和事件很容易达到目的
 
TO:张无忌,

能举例吗?
 
你在dpr文件里如下:
在uses加一个windows;
var
hMutex:THandle;
begin
Application.Initialize;
Application.title:='ProgramA';
hMutex:=GreateMutex(nil,false,'ProgramA');
if GetLastError<>ERROR_ALREADY_EXISTS then
begin
//加入你的生成窗口代码比如 Application.CreateForm(TForm1,Form1);
Application.Run;
end
else
Application.MessageBox('本程序已经运行了,不能再次运行!',MB_ICONINFORMATION);
ReleaseMutex(hMutex);
end;
end;
 
加入Application.title := 'ProgramA'里保存都无法保存,出错:
Error in module xxxx: Call to Application.CreateForm is missing or incorrent.
 
program Project1;

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

const
CM_RESTORE = WM_USER + $1000;

var
RvHandle : hWnd;

{$R *.RES}

begin
{If there's another instance already running, activate that one}
RvHandle := FindWindow('My Delphi program!', NIL);
if RvHandle > 0 then
begin
PostMessage(RvHandle, CM_RESTORE, 0, 0);
Exit;
end;

{Else, do the normal stuff}
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;

end.
// ----------------------------------
// Author : Rob de Veij
// date : 03 oct 1997
// Version : 1.0
// Email : rdv@homemail.com
// ----------------------------------

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

const
CM_RESTORE = WM_USER + $1000;

type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure CreateParams(var Params: TCreateParams); override;
Procedure RestoreRequest(var message: TMessage); message CM_RESTORE;
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

// =========================================
// Override Default RegisterClass Parameters
// =========================================
procedure TForm1.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WinClassName := 'My Delphi Program!';
end;

// ===============================================
// Handle CM_RESTORE Message (Restore Application)
// ===============================================
procedure TForm1.RestoreRequest(var message: TMessage);
begin
if IsIconic(Application.Handle) = TRUE then
Application.Restore
else
Application.BringToFront;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
Label2.Caption := inttohex(Application.Handle, 8);
end;

end.
 
http://www.delphibbs.com/delphibbs/dispq.asp?lid=286670
 
不要这句也可以运行
 
防止多次运行有4种方法:
1. FindWindow查找有无该程序的类名存在.
2. CreateMutex建立个互斥量,再用WaitForSingleObject检查.
3. 注册原子. GlobalAddAtom,GlobalFindAtom
4, CreateSemaphore,WaitForSingleObject
 
谢谢大家!
 
后退
顶部