visual-c++mfcsendmessage

Using SendMessage to get a CString value?


Using SendMessage I can pass a CString up to the parent easily enough (simplified):

CString strText = L"The text";
GetParent()->SendMessage(theApp.UWM_LOADED_SRR_FILE_MSG, 
                        reinterpret_cast<WPARAM>(strText.GetString()));

Parent handler:

afx_msg LRESULT CMyDialog::OnSetSRRFilename(WPARAM wParam, LPARAM lParam)
{
    LPCTSTR szFilename = reinterpret_cast<LPCTSTR>(wParam);

    // Do something.

    return 0;
}

That works, but what about the other way? How can I use messaging to get the current CString value from the parent? I know I can just cast to the parent object type and call the public method. But I want to use messaging. The way I understand it is that SendMessage is passing to a location to receive text.

Am I supposed to post a message to parent that says "i want the string" passing the handle of my window. And then in that handler it sends a message to that handle with the string value?

Am I overcomplicating this?

The string value is not a control, just a private variable.


Solution

  • You can simply define a message asking for the text. The caller (child) must have a buffer to receive the text. wParam can be the buffer length and lParam the buffer (pointer).

    Alternatively, the message return value can be a memory object (handle or pointer) eg allocated by the parent and freed by the child. For an example of how the message could be defined check the WM_GETTEXT message; for the alternative case the GetClipboardData() function.

    Third alternative, the message return-value can be a CString*, containing the requested text. It must be allocated by the parent by calling new, copy-constructed from the original. On return the child "owns" the object and must free it by calling delete. Or the message could just return the address of the CString object, or even its buffer (call GetString()) - in these cases it is considered "read-only" for the child.