memperbolehkan hanya 1 aplikasi instance dalam 1 waktu dgn menggunakan fungsi findwindow()


compiler: delphi:

program Project1;

uses

Forms,

Windows,

Unit1 in ‘Unit1.pas’ {Form1};

var

instHandle: Cardinal;

{$R *.res}

begin

instHandle := FindWindow(‘TForm1’, PChar(formcaption));

if instHandle = 0 then

begin

Application.Initialize;

Application.CreateForm(TForm1, Form1);

Application.Run;

end;

end.

CODE
unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs;

type

TForm1 = class(TForm)

procedure FormCreate(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

formcaption: string = ‘caption’;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);

begin

Caption := formcaption;

end;

end.

apabila dibutuhkan enhancement, misal apabila developer ingin melakukan penanganan/aksi pada instance pertama saat instance kedua mencoba tampil. tambahkan kodenya sehingga menjadi seperti ini:

CODE
program Project1;

uses

Forms,

Windows,

Messages,

Unit1 in ‘Unit1.pas’ {Form1};

var

instHandle: Cardinal;

{$R *.res}

begin

msgunik := RegisterWindowMessage(PChar(strmsgunik));

instHandle := FindWindow(‘TForm1’, PChar(formcaption));

if instHandle = 0 then

begin

Application.Initialize;

Application.CreateForm(TForm1, Form1);

Application.Run;

end

else

SendMessage(instHandle, msgunik, 0, 0);

end.

CODE
unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs;

type

TForm1 = class(TForm)

procedure FormCreate(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

procedure WndProc(var Message: TMessage); override;

end;

var

Form1: TForm1;

msgunik: Cardinal;

strmsgunik: string = ‘unik’;

formcaption: string = ‘caption’;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.WndProc(var Message: TMessage);

begin

if Message.Msg = msgunik then

MessageBox(Self.Handle, ‘aplikasi dah ada’, ‘hanya 1 instance’, 0);

inherited;

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

Caption := formcaption;

end;

end.

aplikasi yg dibuat dgn cara di atas harus mempunyai form, bukan aplikasi console. untuk console, cara paling mudah yaitu dengan menggunakan atom.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: