以下的方法可能是最简单的
type
TMainForm = class(TForm)
// ......
procedure FormCreate(Sender: TObject);
private
procedure CreateParams(var Params: TCreateParams)
override;
Procedure DataRequest(var Msg: TMessage)
message WM_COPYDATA;
end;
const
AppWinClass = 'MyApplication';
var
MainForm: TMainForm;
function AppCanStart: Boolean;
implementation
{$R *.DFM}
type
TDataStru = array [0..2] of DWORD;
PDataStru = ^TDataStru;
function AppCanStart: Boolean;
var
RvHandle: hWnd;
X: TDataStru;
S: FixStr;
begin
RvHandle:= FindWindow(PChar(AppWinClass), nil);
if RvHandle <= 0 then
Result:= True
else begin
Result:= False;
if ParamCount = 0 then S:= '' else S:= ParamStr(1);
X[0]:= 0;
X[1]:= Length(S);
X[2]:= dWord(Addr(S[1]));
S[X[1] + 1]:= #0;
SendMessage(RvHandle, WM_COPYDATA, 0, dWord(Addr(X)));
end;
end;
procedure TMainForm.DataRequest(var Msg: TMessage);
var
P: PDataStru
S: String;
begin
P:= PDataStru(Msg.lParam);
try
S:= PChar(P^[2]);
if Length(S) <> 0 then begin
ShowMessage(S);
// 想做什么?
end;
except
S:= '';
end;
if not Visible then begin
Show;
if WindowState = wsMinimized then WindowState:= wsNormal;
end;
Application.Restore;
Application.BringToFront
end;
procedure TMainForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WinClassName:= AppWinClass;
end;
与之相配合的 DPR 文件如下:
uses
Forms,
MyMainForm in 'MyMainForm.pas' {MainForm};
{$R *.RES}
begin
if AppCanStart then begin
Application.Initialize;
Application.Title := 'MyApplication, Cool!';
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end;
end.