Skip to content
Advertisement

SendMessage only send the *first* character of the string

I am using the following python code to send String to a RAD Studio C++ Builder built application:

import win32con
import win32gui
import ctypes
import ctypes.wintypes  

FindWindow = win32gui.FindWindow
SendMessage = ctypes.windll.user32.SendMessageW

class COPYDATASTRUCT(ctypes.Structure):
    _fields_ = [
        ('dwData', ctypes.wintypes.LPARAM),
        ('cbData', ctypes.wintypes.DWORD),
        ('lpData', ctypes.c_wchar_p) 
    ]

hwnd = FindWindow(None, "SIGNAL")
cds = COPYDATASTRUCT()
cds.dwData = 0

mystr = "This is a message to signal..."

cds.cbData = ctypes.sizeof(ctypes.create_unicode_buffer(mystr))
cds.lpData = ctypes.c_wchar_p(mystr)

SendMessage(hwnd, win32con.WM_COPYDATA, 0, ctypes.byref(cds))

It is perfectly find the opponent application and SendMessage sends data.

My problem: It only sends the 1st character of the string. So instead of: "This is a message to signal..." , it only sends "T".

I am sure that I am overlooking something trivial, but I could not found it.

Advertisement

Answer

To support all may run into the same task/issue, the working “receive” code (RAD Studio C++ builder) is:

void __fastcall Tmain_form::WMCopyData(TMessage& Message)  // Receiving messages from Python script in C++ Builder
{
int DataSize;
wchar_t* Data;

COPYDATASTRUCT* CopyData = reinterpret_cast <COPYDATASTRUCT*> (Message.LParam);

    DataSize = CopyData->cbData;

    if (DataSize > 0)
    {
        Data = new wchar_t[DataSize];
        memcpy(Data, CopyData->lpData, DataSize);

        // Process your data....    
    
        delete [] Data;
    }
}

Just to be complete, this goes to the header file, below ‘protected’:

BEGIN_MESSAGE_MAP
    MESSAGE_HANDLER(WM_COPYDATA, TMessage, WMCopyData)
END_MESSAGE_MAP(TForm)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement