Click here to Skip to main content
13,557,288 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


72 bookmarked
Posted 17 Feb 2010
Licenced CPOL

How to make MessageBoxes center on their parent forms

, 17 Feb 2010
Rate this:
Please Sign up or sign in to vote.
How to make MessageBoxes center on their parent forms.


Everyone uses MessageBox - it's been a fixture of Windows since day 1, and its format and invocation have changed very little over the years.

For me, the single biggest drawback of MessageBox has been that it centers on the screen, not on its parent, and there's no way to tell it to center on its parent:


Here's what I want:


You'd think that at least one of MessageBox.Show()'s 21 overloads would have some way of doing this, or perhaps that there'd be a MessageBoxOptions.CenterOnParent flag, but no such luck.

This article presents a simple mechanism for implementing MessageBoxes that appear centered on their parent.


My technique uses a custom class - I call it MsgBox - that wraps the standard MessageBox.Show call with a Windows hook. The hook is set before popping the MessageBox, the hookproc finds and centers the MessageBox before it's initially displayed, then the hook is released.

For simplicity, my example works only on a single thread. If you have multiple threads that pop MessageBoxes in an uncoordinated fashion, you'll need to add some code to handle that situation.

For additional references/articles, CodeProject has many articles on hooking. Search on "SetWindowsHookEx".

Microsoft's docs are available here:

Using the Code

As mentioned above, the core mechanism is a Windows hook. For the uninitiated, this is a Windows mechanism that allows your code to get access to some low-level Windows functionality; you essentially inject a bit of your app's code into the inner workings of Windows.

There are may types of hooks; my code uses the WH_CBT hook and acts on the HCBT_ACTIVATE event. (Read the Microsoft page linked above for details on WH_CBT.)

Hooks are a not part of .NET. To use them, you must use PInvoke to access the Win32 hooking APIs SetWindowsHookEx(), CallNextHookEx(), and UnhookWindowsHookEx(). These set local hooks, meaning that they only operate on windows within our process. This is exactly what we want - we do not want to handle message boxes displayed by other applications, only our own.

When you set a WH_CBT hook, your callback will receive notifications of window events such as creation, activation, moving/sizing, and destruction. We're interested in activation: when a message box is first activated (but before it's initially visible), we'll reposition it, and then we're done.

The code snippets below are lifted from the attached sample. In them, you'll see me using a Win32.* syntax - in the sample, I've collected all P/Invoke methods and defs in a separate class named Win32, a common practice that I've adopted for my projects.


First, you need to import the hooking APIs:

using System.Runtime.InteropServices;

public class Win32
   public const int WH_CBT = 5;
   public const int HCBT_ACTIVATE = 5;

   public delegate int WindowsHookProc(int nCode, IntPtr wParam, 
                                       IntPtr lParam);

   [DllImport("user32.dll", CharSet = CharSet.Auto, 
              CallingConvention = CallingConvention.StdCall)]
   public static extern int SetWindowsHookEx(int idHook, 
          WindowsHookProc lpfn, IntPtr hInstance, int threadId);

   [DllImport("user32.dll", CharSet = CharSet.Auto, 
              CallingConvention = CallingConvention.StdCall)]
   public static extern bool UnhookWindowsHookEx(int idHook);

   [DllImport("user32.dll", CharSet = CharSet.Auto, 
              CallingConvention = CallingConvention.StdCall)]
   public static extern int CallNextHookEx(int idHook, int nCode, 
                            IntPtr wParam, IntPtr lParam);

and define a few variables for managing the hook:

private int _hHook = 0;
private Win32.WindowsHookProc _hookProcDelegate;
private static string _title = null;
private static string _msg = null;

Setting, processing, and releasing the hook

Create a callback delegate then calls SetWindowsHookEx() to set the hook. It returns a hook ID that you'll use in your callback and when you release the hook.

// Remember the title & message that we'll look for.
// The hook sees *all* windows, so we need
// to make sure we operate on the right one.
_msg = msg;
_title = title;

Win32.WindowsHookProc hookProcDelegate = 
                      new Win32.WindowsHookProc(HookCallback);
_hHook = Win32.SetWindowsHookEx(Win32.WH_CBT, hookProcDelegate, 
         IntPtr.Zero, AppDomain.GetCurrentThreadId()); 

Your hook callback looks something like this. Once you're done processing the notification, you must pass the event along to the next hook via CallNextHookEx(). (Note the use here of your hook ID, _hHook.)

private static int HookCallback(int code, IntPtr wParam, IntPtr lParam)
   if (code == Win32.HCBT_ACTIVATE)
      // wParam is the handle to the Window being activated.
         Unhook();   // Release hook - we've done what we needed
   return Win32.CallNextHookEx(_hHook, code, wParam, lParam); 

Then, finally, when you're done looking for the message box, you release the hook:

private static void Unhook()
   _hHook = 0;
   _hookProcDelegate = null;
   _title = null;
   _msg = null;

Finding your message box

Simply watch for a dialog box which has the correct title and message:

private static bool TestForMessageBox(IntPtr hWnd)
   string cls = Win32.GetClassName(hWnd);
   if (cls == "#32770") // MessageBoxes are Dialog boxes
      string title = Win32.GetWindowText(hWnd);
      string msg = Win32.GetDlgItemText(hWnd, 0xFFFF); // -1 aka IDC_STATIC
         if ((title == _title) && (msg == _msg))
            return true;
   return false;

Centering the message box on its parent form

Centering one window on another - nothing special here:

private static void CenterWindowOnParent(IntPtr hChildWnd)
   // Get child (MessageBox) size
   Win32.RECT rcChild = new Win32.RECT();
   Win32.GetWindowRect(hChildWnd, ref rcChild);
   int cxChild = rcChild.right - rcChild.left;
   int cyChild = rcChild.bottom -;

   // Get parent (Form) size & location 
   IntPtr hParent = Win32.GetParent(hChildWnd);
   Win32.RECT rcParent = new Win32.RECT();
   Win32.GetWindowRect(hParent, ref rcParent);
   int cxParent = rcParent.right - rcParent.left;
   int cyParent = rcParent.bottom -;

   // Center the MessageBox on the Form 
   int x = rcParent.left + (cxParent - cxChild) / 2;
   int y = + (cyParent - cyChild) / 2;
   uint uFlags = 0x15; // SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE;

   Win32.SetWindowPos(hChildWnd, IntPtr.Zero, x, y, 0, 0, uFlags);

and that's about it!

In your calling code, just call MsgBox.Show() instead of MessageBox.Show(), and you'll get parent-centered pop-ups.

Points of Interest

I've frequently wondered why message boxes appear centered on the screen rather than on their parent. I assumed that there must be some method to the madness - Microsoft wouldn't let a bug like this slip for 20 years! (Well, maybe they would... :) )

While developing this code, I found a plausible explanation: say, for example, that your window is positioned outside the display boundaries and an error occurs that pops a message box. In this case, if the message box were centered on its parent, you'd never see it. I think that this is a valid concern, and you should consider it when using centered message boxes, maybe choosing to not parent-center some error messages, just in case.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
United States United States
I can type "while" and "for" very quickly

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
lecedre11-Aug-10 23:28
memberlecedre11-Aug-10 23:28 
GeneralRe: My vote of 1 Pin
megalomania99931-Jan-11 2:14
membermegalomania99931-Jan-11 2:14 
GeneralRe: My vote of 1 Pin
DLChambers31-Jan-11 2:43
memberDLChambers31-Jan-11 2:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03-2016 | 2.8.180515.1 | Last Updated 17 Feb 2010
Article Copyright 2010 by DLChambers
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid