카테고리 없음

[시스템] WM_COPYDATA 메시지를 사용한 IPC 2

쇼핑스크래퍼5 2023. 9. 11. 10:06
This might not be the easiest method of using WM_COPYDATA, but it works...

Assuming you've defined the following for both apps...

type
  WM_MYMESSAGE = WM_USER + 1; // Or register a message if you want to be
safe

type
  TMyData = record
    Name: String[250];
end;

To send the message -

{**********************************************************************}
procedure TMySender.SendData(pLogItem: TLogItem);
var
  pData: TMyData;
  DataStruct: TCopyDataStruct;
begin
  // Put some data into the record
  pData.Name := 'Hello';

  // Build the COPYDATASTRUCT
  DataStruct.dwData := WM_MYMESSAGE;     // This is the user message you'll search for later
  DataStruct.cbData := SizeOf(TMyData);  // Tell it the size of the data it needs to copy
  DataStruct.lpData := @pData;   // Pointer to the data

  // Send the message
  SendMessage(TheOtherHandle, WM_COPYDATA, 0, LParam(@DataStruct)); // Where TheOtherHandle = Handle of the other app
end;

{**********************************************************************}
To receive the message -

type
  TMyMainForm = Class(TForm)
  private
    ...
  protected
    ...
    procedure CopyDataHandler(var wpMessage: TMessage); message WM_COPYDATA;
  public
    ...
end;

procedure TMyMainForm.CopyDataHandler(var wpMessage: TMessage); message
WM_COPYDATA;
var
  pData: TMyData;
begin
  // Check to see if the message is one we've sent
  if (PCopyDataStruct(wpMessage.LParam)^.dwData = WM_MYMESSAGE) then
  begin
    // Copy the data into a local record structure
    CopyMemory(@pData, PCopyDataStruct(wpMessage.LParam)^.lpData, PCopyDataStruct(wpMessage.LParam)^.cbData);

    // Mark the message as processed
    wpMessage.Result := 1;
  end // if (PCopyDataStruct)
end;