Click here to Skip to main content
15,879,535 members
Articles / Desktop Programming / MFC
Article

Sending and posting CString to windows via PostMessage, SendMessage

Rate me:
Please Sign up or sign in to vote.
4.89/5 (13 votes)
1 Sep 20013 min read 1.5M   2.7K   32   18
A robust mechanism for sending CString objects to windows within the current process.

Introduction

On occasions, I have needed to send a CString object to a window in my application via SendMessage or PostMessage (usually PostMessage). I have seen this particular question posted on the message boards several times, so I decided to post the code that I use to deal with this situation.

The Problem

The problem is that for whatever reason, you need to send a message to another window in your application and that message needs to include a CString object (passed via the WPARAM or LPARAM parameters). This is problematic because you must be careful to allocate the CString object on the heap (via the new operator), and you must take care to insure that the CString object is deleted when your application is finished with it. Not only this, but potential problems exist, such as accidentally sending the same message to the target window with no CString object passed in and various other situations.

The Solution

The solution is to use a CString derived class specifically designed to deal with this situation which deals with all of the issues involved in sending CStrings via Windows messaging. The solution involves 2 classes which work together to:

  1. Ensure that CString objects are only sent to windows within the current process (sending to other processes would cause unpredictable problems)
  2. Ensure that CString objects are properly cleaned up after they have been used
  3. Ensure that if the message does not make it to the intended target, that the CString object is not leaked
  4. Ensure that the receiving window does not process the message if the CString object is invalid.
  5. Avoid over-complicating the problem with global variables, CWinApp variables, etc.

The Implementation

I have created 2 classes CMessageString (derived from CString) and CMessageStringManager (not derived from any class). CMessageStringManager is not called directly by the program, it is managed as a protected static member of the CMessageString class.

CMessageString is a public derived class of CString which implements all of the currently defined constructors for CString (from MSDN). CMessageString has a protected static member of CMessageStringManager type. CMessageStringManager consists of a protected member CPtrList, an Add method, Delete method, ForceCleanup function and IsValid function. Each time a CMessageString is constructed, the Add method of CMessageStringManager is called to add the new CMessageString object into the CPtrList. When a CMessageString is destroyed, the Delete method is called to remove it from the CPtrList. When the app closes and the CMessageStringManager class is destroyed, it ensures that there are no CMessageString objects left in the list. If there are, it deletes them and if in debug mode, notifies the programmer through the TRACE macro.

CMessageString implements 5 public methods.

  1. SendAsWParam (HWND hwndTarget, UINT uiMessage, WPARAM wParam)
  2. SendAsLParam (HWND hwndTarget, UINT uiMessage, LPARAM lParam)
  3. PostAsWParam (HWND hwndTarget, UINT uiMessage, WPARAM wParam)
  4. PostAsLParam (HWND hwndTarget, UINT uiMessage, LPARAM lParam)
  5. static IsStringValid (CMessageString* pString)
  6. ForceCleanup ()

How to use these classes

I have included a simple demo project to show how this is used. In order to use these classes in your application, first add the 4 files to your project. To see how a CMessageString is sent, look in the CStringMessageDemoView class. To see how a CMessageString is received, look in the CMainFrame class.

First, include the messagestring.h file in your stdafx.h file (or some other appropriate file, I include it here because is makes it easy to use the class throughout my program).

TO SEND A CMessageString as a message

void SendAString()
{
    CMessageString* pString = new CMessageString;
    (*pString) = "bla.bla.bla";
    pString->PostAsWParam(hwnd, ID_SOME_MESSAGE, 0);
}

TO RECEIVE A CMessageString as a message

LRESULT CSomeWindow::OnStringMessage(WPARAM wParam, LPARAM lParam)
{
    // we expect the CMessageString in the WParam paramater
    CMessageString* pString = (CMessageString*)wParam;
       
    // make sure passed string is valid
    // (this is important to prevent unexpected
    // results if an invalid string is passed)
    if (CMessageString::IsStringValid(pString))
    {
        delete pString;
    }
    else
    {
        ASSERT(FALSE);
        return MESSAGESTRING_NOT_RECEIVED;
    }
    
    return 0;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Alexandre GRANVAUD11-Dec-08 4:41
Alexandre GRANVAUD11-Dec-08 4:41 
GeneralThread Safety Pin
sweetfa11-Jan-07 12:39
sweetfa11-Jan-07 12:39 
QuestionWhy CString on heap for PostMessage?? Pin
montiee6-Feb-06 5:11
montiee6-Feb-06 5:11 
AnswerRe: Why CString on heap for PostMessage?? Pin
Chris Meech6-Feb-06 5:43
Chris Meech6-Feb-06 5:43 
GeneralRe: Why CString on heap for PostMessage?? Pin
montiee6-Feb-06 18:43
montiee6-Feb-06 18:43 
AnswerRe: Why CString on heap for PostMessage?? Pin
Cedric Moonen20-Mar-07 21:35
Cedric Moonen20-Mar-07 21:35 
GeneralThis worked great.... Pin
www.codeproject.com12-May-05 14:02
www.codeproject.com12-May-05 14:02 
Questionhow can i send message to Notepad? Pin
Jagdish Vasani28-Mar-05 18:27
Jagdish Vasani28-Mar-05 18:27 
Generalwww.31show.com/ Pin
Anonymous18-Feb-05 1:23
Anonymous18-Feb-05 1:23 
Generalhttp://www.31show.com/ Pin
Anonymous11-Dec-04 1:02
Anonymous11-Dec-04 1:02 
GeneralHello Sir Little Doubt Using Send Message Pin
ThatsAlok26-Nov-04 20:37
ThatsAlok26-Nov-04 20:37 
QuestionHow to send user defined structure using PostMessage? Pin
ledallam13-Sep-04 18:21
ledallam13-Sep-04 18:21 
AnswerRe: How to send user defined structure using PostMessage? Pin
ThatsAlok26-Nov-04 20:17
ThatsAlok26-Nov-04 20:17 
GeneralRe: How to send user defined structure using PostMessage? Pin
ledallam30-Nov-04 16:51
ledallam30-Nov-04 16:51 
GeneralProblem... Pin
RobJones26-Aug-04 5:15
RobJones26-Aug-04 5:15 
Hello,
When posting alot of messages in a loop it Asserts on the following...

void CPtrList::AssertValid() const
{
	CObject::AssertValid();
 
	if (m_nCount == 0)
	{
		// empty list
		ASSERT(m_pNodeHead == NULL);
		ASSERT(m_pNodeTail == NULL);
	}
	else
	{
		// non-empty list
		ASSERT(AfxIsValidAddress(m_pNodeHead, sizeof(CNode)));
		ASSERT(AfxIsValidAddress(m_pNodeTail, sizeof(CNode))); <<<< Errors here
	}
}

any ideas on why this is happening?

Rob

Whoever said nothing's impossible never tried slamming a revolving door!
GeneralRe: Problem... Pin
RobJones26-Aug-04 7:53
RobJones26-Aug-04 7:53 
Generalpostmessage problem Pin
percyvimal25-Dec-03 18:11
percyvimal25-Dec-03 18:11 
GeneralGreat job.. Pin
RobJones11-Sep-03 8:55
RobJones11-Sep-03 8:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.