Search code examples
c++mfcmessagebox

MFC - MessageBox overload


I'm writing a simple MFC application and I'm noticing something strange:

if I try to use MessageBox function within button event handler, I need of 3 parameters: MessageBox(LPCTSTR, LPCTSTR, UINT);

Instead, if I try to use MessageBox within a function out of form class I need of 4 parameters: MessageBox(HWND, LPCTSTR, LPCTSTR, UINT);

How it works?


Solution

  • This is because CButton inherits from CWnd which contains a method:

    https://msdn.microsoft.com/pl-pl/library/0eebkf6f.aspx

      int MessageBox(
       LPCTSTR lpszText,
       LPCTSTR lpszCaption = NULL,
       UINT nType = MB_OK 
    );
    

    its implementation acutally calls a global version (the second one from your question), HWND used in this call will be taken from the CWnd. You can lookup implementation of this function in MFC sources in your Visual Studio directory, it looks as follows under Visual Studio 2015:

    int CWnd::MessageBox(LPCTSTR lpszText, LPCTSTR lpszCaption, UINT nType)
    {
        if (lpszCaption == NULL)
            lpszCaption = AfxGetAppName();
        int nResult = ::MessageBox(GetSafeHwnd(), lpszText, lpszCaption, nType);
        return nResult;
    }
    

    On the other hand if you call a free function (global one) you must provide hwnd by yourself.

    [edit]

    As xMRi has pointed out in comment, in MFC application AfxMessageBox should be used instead of the MessageBox (both ::MessageBox and CWnd::MessageBox - they are the same). The reason is that AfxMessageBox is MFC dialog box so it plays nicely with whole MFC infrastructure, while ::MessageBox is from WinAPI, which knows actually nothing about MFC.