简体   繁体   中英

How to add a callback in an event handler in a legacy MFC code?

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); 

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 (ie 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM