How to redirect MFC messages to another object?

2019-01-25 22:02发布

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.

4条回答
SAY GOODBYE
2楼-- · 2019-01-25 22:23

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.

查看更多
我只想做你的唯一
3楼-- · 2019-01-25 22:27

I think you need subclassing.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-25 22:31

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(...)

查看更多
做个烂人
5楼-- · 2019-01-25 22:32

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.

查看更多
登录 后发表回答