Title: One instance w/command line passing - Windows API
Question: Running only one instance of your application, and having the commandline of the attempted second instance passed to the already running instance.
Answer:
The previous article on this was pretty good. The only problem is it uses the clipboard. A more straightforward way is using the built in windows messaging. Here is an example:
Thanks Si Carter. I've updated the code;
Last Update: 7 September 2001 11:30 am Central Time
Sender (DPR):
Uses Windows //for HWND, TCopyDataStruct
,VCLUtils //for FindPrevInstance, ActivatePrevInstance
//NOTE: This unit is in RxLib www.rxlib.com (it's free and
// HIGHLY recommended)
//If you don't want RxLib, use FindWindow and
//SetForegroundWindow (in the windows unit) instead of
//FindPrevInstance and ActivatePrevInstance respectively
,Messages; //for WM_CopyData
var
prevInstance : HWND;
cds : TCopyDataStruct;
s : String;
title : String = 'My main form window'; //do this so u can test
//while having design
//window open
begin
prevInstance := FindPrevInstance(TfrmMain.ClassName, title);
if prevInstance 0 then
begin
with cds do
begin
s := CmdLine + #0; //updated 7 sep 2001
cbData := Length(s);
lpData := @s[1];
case someCondition of
1 : dwData := rqRun; //these are defined in the frmMain unit
2 : dwData := rqShowMessage;
end;
end;
ActivatePrevInstance(TfrmMain.ClassName, title);
SendMessage(prevInstance, WM_CopyData, 0, Integer(@cds));
Exit;
end;
Application.Initialize;
Application.CreateForm(TfrmMain, frmMain);
frmReportMain.Caption := title; //do this so u can test while having
//design window open in Delphi
Application.Run;
end.
Receiver (in unit of TfrmMain):
const
rqRun = 1;
rqShowMessage = 2; etc...
In TfrmMain object definition (private, public, etc...):
procedure wmcopydata(var theMsg : TWMCOPYDATA); message
WM_COPYDATA;
procedure TfrmMain.wmcopydata(var theMsg : TWMCOPYDATA);
var
s : String;
begin
with theMsg.CopyDataStruct^ do
begin
s := PChar(lpData);
case dwData of
rqRun : begin
//your code here
end;
rqShowMessage : begin
ShowMessage('You ran with ' + s);
end;
end;
end;