Question

In an instance of a class derived from CWnd, is it possible to forward (redirect) all MFC messages to another object, without writing separate handlers and message mappings for each possible message? Specifically, I'd like to forward all unhandled WM_ messages to another object. If this isn't possible, then is it possible for objects to listen to events that occur within other objects? I can provide details if that would help clarify my question.

Thanks.

Was it helpful?

Solution

You'll need to aim a little lower than MFC. You should override the PreTranslateMessage method of your window and process the messages directly.

Once you have the main message loop, you can pick and choose which ones are handled by your app and which ones are Sent/Posted to another. If you choose to send the message, I'd recommend SendMessageTimeout(...)

OTHER TIPS

I think you need subclassing.

No, you can't really do what you're asking, but you probably don't have to. (Some more details of your problem may be in order.) When you create a message map, you specify both the class to which it applies and the base class for that class. If your derived class doesn't have a message map entry for a particular message, MFC will check the message map for the base class. If the base class message map has no entry, it will check the message map for its base class, and so on.

For example, suppose you have a bunch of dialogs with common functionality. You could lay out your classes thusly:

class CMyBaseDialog : public CDialog {
    DECLARE_MESSAGE_MAP();
}

BEGIN_MESSAGE_MAP(CMyBaseDialog, CDialog)
    // Handle any common messages here...
END_MESSAGE_MAP()

class CDerivedDialog : public CMyBaseDialog {
     DECLARE_MESSAGE_MAP();
}

BEGIN_MESSAGE_MAP(CDerivedDialog, CMyBaseDialog)
    // Handle any specific messages here...
END_MESSAGE_MAP()

The same applies to all other HWND based classes, such as CWnd, CView, CFrame, and so on. If you're dealing specifically with command messages, then you have some additional options.

Well since I can't seem to be able to post a comment I'll post this as an answer. I had a problem following Brad's answer where some WM_COMMANd messages where not routed through the PreTranslateMessage function (see my answer to my question How to stop MFC from disabling my controls if I don't declare a message map entry for it's corresponding command?) but were through OnCommand so basically I overriden the OnCommand function to forward all WM_COMMAND messages too. I'm posting this in case anyone get the same problem.

Anyway thanks for the helps Brad, your answer helped me a lot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top