Mick
Mick

Reputation: 7937

Set location of MessageBox?

I want to print out a message using MessageBox (or similar). I would also like control over where exactly on the screen the box appears but can find nothing in the description of MessageBox that allows you control over the location. Did I miss something? If MessageBox can not be used, then is there an alternative?

For reasons too complex to go into here, I would prefer an answer which didn't involve making my own window and passing the address of a callback function.

Upvotes: 12

Views: 5062

Answers (4)

Blake7
Blake7

Reputation: 2235

Step 1: Create a CBT hook to trap the creation of the message box:

// global hook procedure
HHOOK hhookCBTProc = 0;

LRESULT CALLBACK pfnCBTMsgBoxHook(int nCode, WPARAM wParam, LPARAM lParam)
{
  if (nCode == HCBT_CREATEWND)
  {
    CREATESTRUCT *pcs = ((CBT_CREATEWND *)lParam)->lpcs;

    if (pcs->style & WS_DLGFRAME || pcs->style & WS_POPUP)
    {
      HWND hwnd = (HWND)wParam;

      // At this point you have the hwnd of the newly created 
      // message box that so you can position it at will
      SetWindowPos(hwnd, ...);
    }
  }

  return CallNextHookEx(hhookCBTProc, nCode, wParam, lParam);
}

Step 2: Install/remove the hook before and after showing the message box:

// set hook to center the message box that follows
hhookCBTProc = SetWindowsHookEx(WH_CBT, 
                                pfnCBTMsgBoxHook, 
                                0, GetCurrentThreadId());

int sResult = MessageBox(hwndParent, pszMsg, pszTitle, usStyle);

// remove the hook
UnhookWindowsHookEx(hhookCBTProc);

Upvotes: 17

MSalters
MSalters

Reputation: 179787

MessageBox is a basically a set of defaults. Don't like them? Bring your own. If you don't want a real window with all its complexities, but MessageBox is too restrictring, create a dialog.

Upvotes: 3

Rob
Rob

Reputation: 78628

You could do this with a CBT hook procedure. There is an MSDN article on how to do this in VB but converting it to C++ wouldn't be hard.

http://support.microsoft.com/kb/180936

Upvotes: 1

TalkingCode
TalkingCode

Reputation: 13557

If I needed additional behavior for a Messagebox I always created my own window and made it look like a standard MessageBox. You do it right once and you can always reuse it in other projects.

Upvotes: 5

Related Questions