简体   繁体   English

WM_COPYDATA无法正确传送我的字串

[英]WM_COPYDATA won't deliver my string correctly

I tried to use WM_COPYDATA to send a string from one window to another. 我尝试使用WM_COPYDATA将字符串从一个窗口发送到另一个窗口。 The messaages gets received perfectly by my receiving window. 我的接收窗口将邮件完美地接收了。 Except the string I send does not stay intact. 除了我发送的字符串不会保持原样。

Here is my code in the sending application: 这是我在发送应用程序中的代码:

 HWND wndsend = 0;
 wndsend = FindWindowA(0, "Receiving window");
 if(wndsend == 0)
 {
    printf("Couldn't find window.");
 }

TCHAR* lpszString = (TCHAR*)"De string is ontvangen";
COPYDATASTRUCT cds;
cds.dwData = 1; 
cds.cbData = sizeof(lpszString);
cds.lpData = (TCHAR*)lpszString;
SendMessage(wndsend, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)(LPVOID)&cds);

And this is the code in the receiving application: 这是接收应用程序中的代码:

 case WM_COPYDATA :
    COPYDATASTRUCT* pcds;
    pcds = (COPYDATASTRUCT*)lParam;
    if (pcds->dwData == 1)
    {
        TCHAR *lpszString;
        lpszString = (TCHAR *) (pcds->lpData);
        MessageBox(0, lpszString, TEXT("clicked"), MB_OK | MB_ICONINFORMATION);
    }

    return 0;

Now what happens is that the messagebox that gets called outputs chinese letters. 现在发生的是被调用的消息框输出中文字母。

My guess is that I didn't convert it right, or that I don't actually send the string but just the pointer to it, which gives a totally different data in the receiver's window. 我的猜测是我没有正确转换它,或者我实际上没有发送字符串,而只是发送指向它的指针,这在接收器的窗口中提供了完全不同的数据。 I don't know how to fix it though. 我不知道如何解决它。

sizeof(lpszString) is the size of the pointer, but you need the size in bytes of the buffer. sizeof(lpszString)是指针的大小,但是您需要缓冲区的大小(以字节为单位)。 You need to use: 您需要使用:

sizeof(TCHAR)*(_tcsclen(lpszString)+1)

The code that reads the string should take care not to read off the end of the buffer by reading the value of cbData that is supplied to it. 读取字符串的代码应注意不要通过读取提供给它的cbData的值来读取缓冲区的末尾。

Remember that sizeof evaluates at compile time. 请记住, sizeof在编译时求值。 Keep that thought to the front of your mind when you use it and if ever you find yourself using sizeof with something that you know to be dynamic, take a step back. 使用它时,请先将其放在脑海中,如果您发现使用sizeof结合了一些您知道是动态的东西,请退后一步。

As an extra, free, piece of advice I suggest that you stop using TCHAR and pick one character set. 作为一项额外的免费建议,我建议您停止使用TCHAR并选择一个字符集。 I would recommend Unicode. 我建议使用Unicode。 So, use wchar_t in place of TCHAR . 因此,使用wchar_t代替TCHAR You are already building a Unicode app. 您已经在构建Unicode应用程序。

Also, lpData is a pointer to the actual data, and cbData should be the size of the data, but you're actually setting the size of the pointer. 另外, lpData是指向实际数据的指针, cbData应该是数据的大小,但是实际上是在设置指针的大小。 Set it to the length of the string instead (and probably the terminating 0 character too: strlen(lpszString)+1 而是将其设置为字符串的长度(也可能也是终止符0: strlen(lpszString)+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM