简体   繁体   中英

How do I copy data from one windows app to another?

I need to transfer data in win api from one application to another. In one app I have:

msg_number=RegisterWindowMessage(MY_WINDOW_MSG);
cp_struct.lpData = &fig;
cp_struct.dwData = sizeof(Figure);
cp_struct.cbData = 6666;
SendMessage(HWND_BROADCAST, msg_number, 0, (LPARAM)&cp_struct); 

In another:

case WM_CREATE:
{
    msg_number=RegisterWindowMessage(TEXT(MY_WINDOW_MSG));  
}
if(msg_number != 0 && msg == msg_number)
{
    reciver_struct = (PCOPYDATASTRUCT)(lParam);
    printf("get it %d\n", reciver_struct->cbData);
    return 0;
}

But in this receiver application, I see that app get the message but not with the values from my struct.

You have the right idea, but you are using the wrong message. You need to assign the value from RegisterWindowMessage() to cp_struct.dwData , assign your data's byte length to cp_struct.cdData , and then send cp_struct using the WM_COPYDATA message (you need to use the other app's actual HWND , not HWND_BROADCAST ), eg:

msg_number = RegisterWindowMessage(MY_WINDOW_MSG); 
if (msg_number != 0)
{
    cp_struct.dwData = msg_number; 
    cp_struct.lpData = &fig; 
    cp_struct.cbData = sizeof(Figure); 
    SendMessage(hWnd, WM_COPYDATA, 0, (LPARAM)&cp_struct);  
}

.

case WM_CREATE: 
{ 
    msg_number = RegisterWindowMessage(MY_WINDOW_MSG);
    break;
} 

case WM_COPYDATA:
{
    reciver_struct = (PCOPYDATASTRUCT)(lParam); 
    if ((msg_number != 0) && (reciver_struct->dwData == msg_number))
    { 
        Figure *figure = (Figure*) cp_struct.lpData; 
        ... use figure as needed ...
        return 0; 
    } 

    ... pass the message to a default handler for processing ...
    break;
}

Correct, you cannot read from the protected memory space of another application. Any pointer or reference that you pass is going to be invalid and useless from the context of the receiving application.

You could use something like ReadProcessMemory to make this work, but that's going to take some actual effort.

It's much simpler to just let Windows take care of the hard work for you by using the WM_COPYDATA message. An example is available here .

Careful, though: WM_COPYDATA is blocked by UIPI in Windows Vista and later. You'll need to white-list this particular message by calling the ChangeWindowMessageFilter function (on Vista) or the ChangeWindowMessageFilterEx function (on Win 7 or later).

If you have access to Boost, consider Boost.Interprocess . If you don't have access to boost, you can use any number of Win API methods for IPC .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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