Naletio sam na jednu glupost oko koje moj mozak odbija pronaci
rjesenje
Stoga vas molim za misao vodilju
Tema: Single instance only
Cilj:
- Zelim da mi ponovo pokretanje aplikacije otvori vec pokrenutu
aplikaciju
( u ovom slucaju treba otvoriti Form2 vec pokrenute aplikacije, a nova
aplikacija prestaje s radom)
Problem:
- U staroj aplikaciji je ShowMainForm:=False, pa SendMessage nikad
nije stigao do mog handlera
Napomena:
-Ako je ikako moguce, volio bih ostaviti ShowMainForm:=False (pravi
program se stavlja u systray)
Ako pricam gluposti, RTFM odgovor je OK, samo me uputite na
literaturu.
Okolina: Delphi 7
Kod za SendMessage je sa
delphi.about.com (malo modificiran)
Pojednostavljena verzija setupa je ova
-------------------
program Project1;
uses
Windows,
Forms,
Unit1 in 'Unit1.pas' {Form1},
Unit2 in 'Unit2.pas' {Form2};
{$R *.res}
var
Mutex : THandle;
begin
// Allow only one instance to run
MyMsg := RegisterWindowMessage('WM_Test');
Mutex := CreateMutex(nil, True, 'mutex_Test');
if (Mutex = 0) OR (GetLastError = ERROR_ALREADY_EXISTS) then begin
SendMessage(HWND_BROADCAST, MyMsg, 0, 0);
end
else begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.CreateForm(TForm2, Form2);
Form1.AppInit;
Application.Run;
if Mutex <> 0 then
CloseHandle(Mutex);
end;
end.
-------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
public
{ Public declarations }
procedure AppInit;
end;
var
Form1: TForm1;
MyMsg: Cardinal;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.AppMessage(var Msg: TMsg; var Handled: Boolean);
begin
if Msg.Message = MyMsg then begin
// U principu ovo treba napraviti Form2.Show;
// no ne znam da li radi jer ne dodje do ovdje
Application.Restore;
SetForeGroundWindow(Application.MainForm.Handle);
Handled := true;
end;
end;
procedure TForm1.AppInit;
begin
// Hide main window
Application.ShowMainForm:=False;
// run on startup
Form2.Show;
end; {AppInit}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Register message to the application
Application.OnMessage := AppMessage;
end;
end.
-------------------
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs, StdCtrls;
type
TForm2 = class(TForm)
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.btn1Click(Sender: TObject);
begin
Application.Terminate;
end;
end.