Jepe d Hepe
Jepe d Hepe

Reputation: 909

MessageBox.Show()

I would like to Show my Messagebox in the center of its parent form. if i move the form and show the messagebox, it always show in the center of the desktop. i want it to appear along with the form. Can you give me some tricks and advice?

Upvotes: 9

Views: 15826

Answers (5)

AH.
AH.

Reputation: 3091

I made this class based on a class for Windows Forms which I found somwehere else.

Just add the class to your WPF project and provide "this" as a parameter to the helper method like this:

  MessageBoxHelper.PrepToCenterMessageBoxOnForm(this)" 

Then show the message box:

MessageBox.Show("Hello there!");


/// <summary>
/// This class makes it possible to center a MessageBox over the parent dialog.
/// Usage example:
///         MessageBoxHelper.PrepToCenterMessageBoxOnForm(this);
///         MessageBox.Show("Hello there!);
/// </summary>
public static class MessageBoxHelper
{
    public static void PrepToCenterMessageBoxOnForm(Window window)
    {
        MessageBoxCenterHelper helper = new MessageBoxCenterHelper();
        helper.Prep(window);
    }

    private class MessageBoxCenterHelper
    {
        private int messageHook;
        private IntPtr parentFormHandle;

        public void Prep(Window window)
        {
            NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
            GCHandle.Alloc(callBackDelegate);
            parentFormHandle = new WindowInteropHelper(window).Handle;
            messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
        }

        private int CenterMessageCallBack(int message, int wParam, int lParam)
        {
            NativeMethods.RECT formRect;
            NativeMethods.RECT messageBoxRect;
            int xPos;
            int yPos;

            if (message == 5)
            {
                NativeMethods.GetWindowRect(parentFormHandle, out formRect);
                NativeMethods.GetWindowRect(new IntPtr(wParam), out messageBoxRect);

                xPos = (int)((formRect.Left + (formRect.Right - formRect.Left) / 2) - ((messageBoxRect.Right - messageBoxRect.Left) / 2));
                yPos = (int)((formRect.Top + (formRect.Bottom - formRect.Top) / 2) - ((messageBoxRect.Bottom - messageBoxRect.Top) / 2));

                NativeMethods.SetWindowPos(wParam, 0, xPos, yPos, 0, 0, 0x1 | 0x4 | 0x10);
                NativeMethods.UnhookWindowsHookEx(messageHook);
            }

            return 0;
        }
    }

    private static class NativeMethods
    {
        internal struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        internal delegate int CenterMessageCallBackDelegate(int message, int wParam, int lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool UnhookWindowsHookEx(int hhk);

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("kernel32.dll")]
        internal static extern int GetCurrentThreadId();

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern IntPtr SetWindowsHookEx(int hook, CenterMessageCallBackDelegate callback, IntPtr hMod, int dwThreadId);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    }
}

Upvotes: 2

JohnB
JohnB

Reputation: 18982

Here is a very easy to use solution, and it works perfectly:

Steps:

  1. Copy and paste that class into your project. I used it without any editing.
  2. To use the modified MessageBox, use this line of code in your project:

(inside a UserControl or a Form)

MessageBoxEx.Show(this, "Please fix the validation errors before saving.", "Validation Errors");

Upvotes: 0

Yogesh
Yogesh

Reputation: 14608

The best way to do this is to use Window Hooks and center the message box yourself. There is a perfect article which shows this usage.

You can find it here: http://www.codeproject.com/KB/dialog/CenterDialog.aspx

You can also use the class in your application without diving in too deep to find out how it actually works.

Upvotes: 3

ChrisBD
ChrisBD

Reputation: 9209

I have done this before in C#. Here's what I remember.

Define a class:

public class IWindowWrapper : System.Windows.Forms.IWin32Window
{
    public IWindowWrapper(IntPtr handle)
    {
        this.Handle= handle;
    }

    public IntPtr Handle
    {
        get; 
        set;
    }
}

Define a class based on MessageBox. Create a class based on MessageBox and create a new Show method :

public string Show(IWin32Window owner)
{
   if(owner == null)
   {
    this.ShowDialog();
   }
   else
   {
      //parentWindow.
      this.StartPosition = FormStartPosition.CenterParent;
      this.ShowDialog(owner);
   }

}

In your calling code (here it is assumed to be a winform and msgBox is based on the new message box class) call the new Show method and pass an IWindowWrapper instance on Show e.g.

msgBox.Show(new IWindowWrapper(this.Handle))

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993085

Set the owner of the message box window to your window (using the first parameter of .Show()), instead of not setting an owner.

See here for a reference.

Upvotes: 1

Related Questions