向所有窗口广播自定义消息。只有您的窗口知道如何对它做出反应。然后它可以在另一条消息中回复其当前的 HWND,因此广播公司不必手动寻找它。使用 RegisterWindowMessage() 注册其他应用程序将忽略的唯一消息 ID。例如:
应用 1:
var
WM_WHERE_ARE_YOU: UINT = 0;
WM_HERE_I_AM: UINT = 0;
App2Wnd: HWND = 0;
procedure TApp1Form.FromCreate(Sender: TObject);
begin
// use whatever string names you want, as long as they match App 2...
WM_WHERE_ARE_YOU := RegisterWindowMessage("WhereAreYou");
WM_HERE_I_AM := RegisterWindowMessage("HereIAm");
end;
procedure TApp1Form.WndProc(var Message: TMessage);
begin
if (Message.Msg = WM_HERE_I_AM) and (WM_HERE_I_AM <> 0) then
App2Wnd := HWND(Message.LParam)
else
inherited;
end;
procedure TApp1Form.SendData(const copyDataStruct: TCopyDataStruct);
var
res : integer;
procedure FindApp2Window;
var
Ignore: DWORD;
begin
App2Wnd := 0;
if WM_WHERE_ARE_YOU = 0 then Exit;
SendMessageTimeout(HWND_BROADCAST, WM_WHERE_ARE_YOU, 0, Longint(Self.Handle), SMTO_NORMAL, 500, Ignore);
if App2Wnd = 0 then Application.ProcessMessages;
end;
begin
FindApp2Window;
if App2Wnd = 0 then
begin
ShowMessage(Format('Unable to find MainForm');
Exit;
end;
res := SendMessage(App2Wnd, WM_COPYDATA, Longint(Self.Handle), Longint(@copyDataStruct));
...
end;
应用 2:
var
WM_WHERE_ARE_YOU: UINT = 0;
WM_HERE_I_AM: UINT = 0;
procedure TApp2Form.FromCreate(Sender: TObject);
begin
// use whatever string names you want, as long as they match App 1...
WM_WHERE_ARE_YOU := RegisterWindowMessage("WhereAreYou");
WM_HERE_I_AM := RegisterWindowMessage("HereIAm");
end;
procedure TApp2Form.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_COPYDATA:
begin
if PCopyDataStruct(Message.LParam)^.dwData = ... then
begin
...
Message.Result := 1;
Exit;
end;
end;
...
else
if (Message.Msg = WM_WHERE_ARE_YOU) and (WM_WHERE_ARE_YOU <> 0) then
begin
if WM_HERE_I_AM <> 0 then
PostMessage(HWND(Message.LParam), WM_HERE_I_AM, 0, Longint(Self.Handle));
Exit;
end;
end;
inherited;
end;