How to redirect MFC messages to another object?

烈酒焚心 提交于 2019-12-18 05:14:08

问题


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.


回答1:


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




回答2:


I think you need subclassing.

  • SubclassWindow()
  • CodeProject article



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/978071/how-to-redirect-mfc-messages-to-another-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!