HOWTO: MFC user defined message maps

We will add the user defined message WM_FIND, identified by the string literal "MYMESSAGE", to a Document/View MFC application. First of all, the message can only be posted to objects of class CWnd or classes derived from CWnd, i.e. actual windows. This makes sense; only windows can receive window messages. Also note, that the class wizard CANNOT be used to introduce message maps for user defined messages. This task must be completed manually.

IN THE VIEW CLASS HEADER FILE

Add the prototype for the function to which the message is to be mapped. This function will be named "On" + (Second half of message name), here: "OnFind()". Further, the function declaration will be preceded by the term "afx_msg". We will define this function to be of type LRESULT (32 bit identifier) , and take the parameters (WPARAM wParam, LPARAM lParam), the standard window messaging parameters. The reason for this lies in the macro expansion of the AFX message map. If your function is not declared in compliance with the AFX message map macro, you will get error C2642.

Look for a section of code like this:

	// Generated message map functions
	protected:
	//{{AFX_MSG(CMyView)
	afx_msg void OnFileConfig();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

Add the following line to the above list of function declarations:
	afx_msg LRESULT OnFind(WPARAM wParam, LPARAM lParam);

IN THE VIEW CLASS BODY FILE

Register the new window message. The string literal will later be used to retrieve the number allocated to WM_FIND.

Add the following line somewhere at the top of the file:

	int WM_FIND = RegisterWindowMessage ("MYMESSAGE");

Map the message onto a member function. The AFX message map entry must use the key word ON_REGISTERED_MESSAGE, and associate the message number with the function name.

Look for a section of code like this:

	BEGIN_MESSAGE_MAP(CMyView, CListView)
	//{{AFX_MSG_MAP(CMyView)
	ON_COMMAND(ID_FILE_CONFIG, OnFileConfig)
	//}}AFX_MSG_MAP
	END_MESSAGE_MAP()

Add the following line to the above list of message maps:

	ON_REGISTERED_MESSAGE(WM_FIND, OnFind)

Add a message handler function to the class. Replace "CMyView" with the class name of the view class in your application:

LRESULT CMyView::OnFind(WPARAM wParam, LPARAM lParam)
{
	// do something useful

	return (LRESULT) MyReturnValue;
};

IN THE DOCUMENT CLASS HEADER FILE

Provide the document class that is to post the message with scope to the view class window handle.

Add a member to hold a window handle.

	HWND PostToView;

IN THE VIEW CLASS BODY FILE

Obtain a reference to the document associated with the view and initialize the document's member variable (above) with the handle to the view's window.

Add the lines shown below to a member function that will be executed before the user message is posted to the view. Replace "CMyDoc" with the class name of your document class. This assignment cannot take place in the view's constructor. The OnCreate() member, however, would be a great place.

	"CMyDoc"* DocPtr = GetDocument();
	DocPtr->PostToView = this->m_hWnd;

IN THE DOCUMENT CLASS BODY FILE

Where you want to post the message, retrieve the reference to WM_FIND, the user defined message and then post the message...

A second call to RegisterWindowMessage() with the same string literal as an argument will retrieve the previously assigned ID for WM_FIND.

Add the code shown below in a function member of the document class from which you wish to post a message. Substitute the question marks for your actual parameters.

	int WM_FIND = RegisterWindowMessage ("MYMESSAGE");

	PostMessage(PostToView,   // handle to view window
	WM_FIND,                  // message to post
	(WPARAM) "?",             // window message parameter
	(LPARAM) "?");            // window message parameter

Alternatively, you can use SendMessage(). In contrast to PostMessage, which sends the message `spiraling' through the Windows messaging system and returns control to the calling thread before the message is actually processed, SendMessage will invoke the target message handler before returning execution control to the caller of SendMessage. The first is appropriate for asynchronous, de-coupled processing, the latter for synchronous processing.



Comments

  • Introducing the Jumpman logo, elephant strong situated and identifiable Exhausted the drum in behalf of to the Jordan postal usable jokesmith would bear viewer to moneymaking with this substantive guess

    Posted by koltchddt on 04/16/2013 11:18am

    A downright of 141 items of clothing were purchased in April 2012 in 29 countries [url=http://www.hollistercovfrance.fr]hollister[/url] and regions worldwide from authorised retailers. The chemicals cause wide included tanked levels of toxic phthalates [url=http://www.abercrombiesfrancevparise.fr]abercrombie paris[/url] in four of the garments, and cancer-causing amines from the disdain of traditional azo dyes in two garments. NPEs [nonylphenol ethoxylates] were institute in 89 garments (upright under two thirds of those tested), showing [url=http://www.airjordanfrpaschera.fr]air jordan[/url] only somewhat respectability from the results of the anterior to experimentation into the air of these substances in sports clothing that was conducted in 2011. In addendum, the vicinity of various other another types of potentially touchy industrial chemicals was discovered across [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] a host of the products tested. The Nakate Engagement also works to conceive artisans in agricultural areas [url=http://www.airjordanspasuchera.fr]jordan[/url] of Uganda that we protection as theretofore untapped or undervalued. They endure in providing profits for the sake women that are struggling to put against themselves [url=http://www.hollisterfrancevmagusin.fr]hollister[/url] and, on assorted of them, the families that are relying on their income. The shoot also adheres to impartial barter principles and environmentally generation practices [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie[/url] including maximizing the avail oneself of of uncovered materials from sustainably managed sources, buying locally where possible and encouraging our artisans to importune in environments of their choosing – which are constantly in the obtainable [url=http://www.monclerfranceumagasinsfr.com]moncler[/url] air. Don’t like your legs? Do you fondle that your legs are too short? Too beamy [url=http://www.airjordanzchaussuren.com]air jordan[/url]? Too white? Whatever your purpose, you don’t like your legs and don’t yearn anyone else to look at them when wearing a deck out, shorts, or a skirt [url=http://www.michaelukorsua.com]michael kors outlet[/url]. No problem! A ruffled crest resolve indisputable the problem. Be indubitable to cynosure unclouded all the perturbation on your ascendancy half and manifest a downland, unassuming bottom.Got an hourglass figure? If so, on the condition that you! While you [url=http://www.hollisterucoboutiques.fr]hollister france[/url] can sensibly undergo up anything you longing, you should peace watch out of ruffles. You don’t indigence to rub off last ruffles on your curves to roll them dotty proportion. In desire to, mar them here your sleeves, collar, or [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] fundament hem.

    Reply
  • La plupart de bienvenue prime customarily les talons hauts etoiles: Christian Louboutin Supervised

    Posted by Vetriatszy on 03/14/2013 05:55am

    Abercrombie en people from france and thus Fitch Vous Faire Suivre l'ensemble des Tare generallydances De option Maintenant supplmbonustaires et trendy england abercrombie and as well cuando stylishness Fitch a publi mme dom le march le nos jours. Partage diffrents shapes diffrent faire briller l'astigmatisme dans l'instant, l. a,chicago femelle s'av'e rrtre maintenant extrmement lgant et luxueux. Dans la poursuite prs de strive and consequently supplmentaire et. le monde des marques bien connues Abercrombie and so Fitch reprsente un format de setting, Une setting de la vie relle. Elle vous indique annotate le type of p haut niveau ne se limite pas dans le lans s capacits l'artisanat a montr proximit scne T. fashion peut peut-Tre partout proximit pour are generally scne. Vous produisez des choix concernant l. a,chicago beaut. Mais serve peu prs n'importe quelle femme, Placer sur ce, Tt ou tard pourrait tre sans doute la fte not to mention pour esthtique essentielle proximit journe. promote comme mtier n'est pas pas connu mme si dans the muse, Isol an elemen le monde extrieur, Le pattern n'est pas seulement mentionn dans le sens nufactured l'brille T-scne. Comme prolonge lorsque vous tes avec Abercrombie Fitch, Vous pouvez nanmoins participer des movements esthtiques proximit de la setting utile. serve les personnes qui dtidurantenunited nationst l. a,chicago proche de proximit proche de build Abercrombie Fitch utilisant le you can find out more mnge de jupe automne et hiver, Avec kid interprtation proche delaware los angeles way of life corss parcours tout-Amricaine, Il that simplement une dpression little, un peu indisciplins et occasionnels, Seulement n'te sduisante petite ou simplement loisir minuscules. Maintenant les choses very et cuando lgante libre mme trendiness le march le nufactured nos jours. Partage diffrents sorts diffrent faire briller l'astigmatisme dans l'instant, l. a,chicago femelle se 'vrrle rrtre maintenant extrmement lgant et luxueux. it gives unique approaches to the product's home owners according to ones adequate company. may full plan arrangement institution that the majority of renders supplements which include corporate headquarters credit. it's important to learn price tag Free stages of most recent clothes and devices that can become so popular-so fast this type of year's bunch of males athletic shoes m. often, they can not showcase which by way of many top reasons

    Reply
  • Problem Posting RegisteredMessages

    Posted by Legacy on 11/29/2003 12:00am

    Originally posted by: David

    I have a CDialog Based Application, where I use a RegisteredMessage to comunicate it with a thread, if I
    post the message from the thread using one XPropertyPage
    Library, nothing is sent but I get no error from PostMessage, if I post the message without using XPropertyPage Library, everything works fine, any idea of what is happenning?

    thanks in advance.

    Reply
  • Use ::PostMessage for PocketPC

    Posted by Legacy on 10/26/2001 12:00am

    Originally posted by: John Jorsett

    Windows CE 3.0 has two forms of PostMessage. To get the one that accepts a window handle argument, use ::PostMessage.

    Reply
  • Thanks this stopped me tearing my own hair out

    Posted by Legacy on 02/10/2001 12:00am

    Originally posted by: Simon Aldrich

    Just to let you know, this worked a treat for me, sending messages between MFC dialogs in the main app and ancillary dlls.

    Thanks so much.

    Simon

    Reply
  • dest . windows handle

    Posted by Legacy on 02/15/2000 12:00am

    Originally posted by: chengchun

    you can SendMessage((HWND)-1,WM_find,wparam,lparam))

    Reply
  • is there any difference between non-MFC and MFC messaging?

    Posted by Legacy on 09/20/1999 12:00am

    Originally posted by: odessa

    my way of using message in MFC framework is different in some point. my method is based on classical user-defined message passing, but yours is something structural, i think.
    i wonder if there is any difference between non-MFC message and MFC messaging.
    my question is why should we use ON_REGISTERED_MESSAGE macro? i use ON_MESSAGE(WM_MY_MESSAGE, OnMyHandler) instead of it. is there any reason for that?


    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

  • You probably have several goals for your patient portal of choice. Is "community" one of them? With a bevy of vendors offering portal solutions, it can be challenging for a hospital to know where to start. Fortunately, YourCareCommunity helps ease the decision-making process. Read this white paper to learn more. "3 Ways Clinicians can Leverage a Patient Portal to Craft a Healthcare Community" is a published document owned by www.medhost.com

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds