Start New Discussion within our Software Development Community

Basically I'm running into issue, I have a Global Keyboard hook in a DLL, whenever it captures a key it uses WMCopyData to send the keycode over to the MAIN application. The problem is when the main application gets the key code it seems to be corrupt/changes in value.

Here is my code for the DLL sending the data:

Procedure PassData(wParamCopy : Word);
Var
  SendStr : String;
      CopyDataStruct : TCopyDataStruct;
      RecHandle : THandle;
Begin
    SendStr := IntToStr(wParamCopy);
    CopyDataStruct.dwData := 0;
    CopyDataStruct.cbData := 1 + Length(SendStr);
    CopyDataStruct.lpData := PChar(String(SendStr));

    RecHandle := GetHandle('AppName');
    If RecHandle = 0 Then
      Begin
        ShowMessage('Communication Error!');
        Exit;
      End;
    SendMessage(RecHandle, WM_COPYDATA, 0, Integer(@CopyDataStruct));
  End;

Recieving code in the main application:

Procedure TfrmMain.WMCopyData(var Msg: TWMCopyData);
Var
  S : String;
Begin
  S := PChar(Msg.CopyDataStruct.lpData);
  ShowMessage(S);
End;

Also a private declaration in the main application goes like this:

Procedure WMCopyData(var Msg : TWMCopyData); Message WM_COPYDATA;

Now say the DLL returns "65" as the keycode when the user press the "A" button, it will pass on the integer type 65 to the "PassData" procedure which will convert it into a string and then into a PChar ready to be sent over to the main applicaiton.

When it does the "ShowMessage(S)" in the main application it ends up showing "65껾玧" clearly something went wrong in the conversion/data sending, can anyone help me out?

Nevermind got it to work, silly me using the tutorials I should have known that cbData was a memory type. I was basically allocating an incorrect amount of memory for the cbData, the correct calculation for that line is:

CopyDataStruct.cbData := (1 + Length(SendStr))*SizeOf(Char);
This article has been dead for over six months. Start a new discussion instead.