Home > Back-end >  How to add a callback in an event handler in legacy a MFC code?
How to add a callback in an event handler in legacy a MFC code?

Time:06-16

This is a toy implementation of a legacy code using MFC. OnBnClickedButton is an event handler but it contains codes which are executed asynchronously in a different thread ( may be a bad idea). The declaration syntax is accepted by the message map.

//declaration
afx_msg void OnBnClickedButton(); 
//message map
ON_BN_CLICKED(IDC_BUTTON, &CMFCApplicationDlg::OnBnClickedButton)

Now I want to add a callback to the event handler like so, but the message-map won't accept the new declaration syntax, where to go?

afx_msg void OnBnClickedButton(std::optional<std::function<CString(void)>> callback); 

CodePudding user response:

The function signatures and return values for entries in MFC message maps are fixed. You have to follow the protocol; it doesn't offer any customization points. In case of the ON_BN_CLICKED button handler the prototype must abide to the following signature

afx_msg void memberFxn();

It doesn't accept or return any values. The only state available is that implied from the message map entry (i.e. OnBnClickedButton is called whenever the child control of the dialog represented by CMFCApplicationDlg with ID IDC_BUTTON is clicked).

In your implementation of OnBnClickedButton you are free to do whatever you like, such as querying for additional information (e.g. from data stored in the class instance or thread-local storage), spinning up threads, either explicitly or using C 20 coroutines, etc.

MFC doesn't help you with any of that, specifically it doesn't provide any sort of support for asynchronous operations. That's something you will have to implement yourself.

  • Related