MFC - MessageBox overload

1.7k Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On

As Steve wrote, one is being called within the overridden method of a CWnd derived class, the other is being called in global scope or at least not in the scope of a CWnd derived class which causes the difference.

For MFC, I would reccommend using AfxMessageBox() everywhere when you want to use a message box. If at some point down the line you need to hook it, there are some tricks you can do.

0
On

I'd say inside the handler your calling CWnd::MessageBox and outside ::MessageBox.