Posts tagged WM_COPYDATA

How to check whether the window handle is valid?

2


Since communication by messages are so easy, windows used to communicate with each other by using messages. For instance, if simple data blocks are to be transfered – WM_COPYDATA can be used. For all those instances the window should be alive. But how to know whether the current window handle is valid or whether it points to a dead window?


You can call the api – IsWindow() by passing window handle. If the handle points to a live window, then the function returns true else false. Have a look at the code snippet.

// The handle to be tested.
HWND hWindow = GetSafeHwnd();

// Check whether the window is still there.
BOOL bWindowAlive = IsWindow( hWindow );


While digging for the api, i found an interesting info. What about window handle re-cycling? For instance you have a window handle and you’re going to check that window by calling IsWindow() function. But in between that the real window is closed and a new window is created. Whether the window handler will be allocated to the new window?

Well, the answer is here. Have a look at it. Its interesting. The oldnewthing. ;)


Targeted Audience – Beginners.

WM_COPYDATA can be used as simple IPC mechanism.

3


Sending and receiving data between processes are one of the greatest headaches that we face. For that many mechanisms are there – such as COM, Sockets, but a bit complicated… There is comparatively simple mechanism for doing the same. i.e. WM_COPYDATA window message.


For IPC communication between two processes, you just need a hidden window created in each and by using the window handle in target process you can send data to it. For sending data via WM_COPYDATA, the following are requirements.

WPARAM – Handle of window in target process.
LPARAM – Pointer to COPYDATASTRUCT which contains data to be exported.

Please see the following code block about how to use it.

void CMyDialog::SendData( HWND hTargetWindow_i,
void* pData_i,
DWORD dwSize_i )
{
// structure holding data information.
COPYDATASTRUCT stCopyData = { 0 };
stCopyData.lpData = pData_i;
stCopyData.dwData = dwSize_i;

// Send the data.
SendMessage( WM_COPYDATA,
(UINT) hTargetWindow_i,
(ULONG) &stCopyData );
}

In the receiving Window, if you are using MFC, you need to handle the WM_COPYDATA message by adding message handle using ON_WM_COPYDATA() and handler function with proto -

afx_msg BOOL OnCopyData( CWnd* pWnd,
COPYDATASTRUCT* pCopyDataStruct );


Targeted Audience _ intermediate.

Go to Top