Using SendData results in a garbled string on receipt

I am trying to send a line between two Delphi formats using the code adapted here: http://delphi.about.com/od/windowsshellapi/a/wm_copydata.htm .

The string displayed by the recipient is partially garbage. I suspect this is because Unicode occurs when Delphi 2010 interacts with the Windows API.

I want to be able to handle Unicode if possible.

I was not able to figure out where in the code below the cast is incorrect. Any help?

Submitting form:

procedure TForm1.gridDetailsDblClick(Sender: TObject);
var
  StringToSend : String;
  CopyDataStruct : TCopyDataStruct;
begin
  StringToSend := StringGrid1.Cells[0, StringGrid1.Row];
  CopyDataStruct.dwData := 0;
  CopyDataStruct.cbData := 1 + Length(StringToSend) ;
  CopyDataStruct.lpData := PChar(StringToSend) ;
  SendDataToAppearanceForm(copyDataStruct) ;
end;

procedure TForm1.SendDataToAppearanceForm(const CopyDataStruct: TCopyDataStruct) ;
var
  ReceiverHandle : THandle;
begin
  ReceiverHandle := FindWindow(PChar('TForm2'), nil);
  if (ReceiverHandle <> 0) then
    SendMessage(receiverHandle, WM_COPYDATA, Integer(Handle), Integer(@CopyDataStruct)) ;
end;

Form of receipt: (which leads to the fact that the edit field contains part of the line, but then garbage.)

procedure TForm2.WMCopyData(var Msg: TWMCopyData);
var
  S: String;
begin
  edText.Text := PChar(Msg.CopyDataStruct.lpData);
end;  { WMCopyData }
+3
source share
2 answers

, cbData. , .

+1, . :

(1 + Length(StringToSend))*SizeOf(Char)

SetString() cbData, +1.

+5

procedure TForm1.Button1Click(Sender: TObject); // Project1.exe
var
  CDS: TCopyDataStruct;
begin
  CDS.dwData := 0;
  CDS.cbData := (length(Edit1.Text) + 1) * sizeof(char);
  CDS.lpData := PChar(Edit1.Text);

  SendMessage(FindWindow(nil, 'RecForm'),
    WM_COPYDATA, Integer(Handle), Integer(@CDS));
end;

procedure TForm1.WndProc(var Message: TMessage); // Project2.exe
begin
  inherited;
  case Message.Msg of
    WM_COPYDATA:
      begin
        Edit1.Text := PChar(TWMCopyData(Message).CopyDataStruct.lpData);
        Message.Result := Integer(True);
      end;
  end;
end;

, . , , , cbData , , sizeof(char). , , ! , !

+2

All Articles