Center MessageBox in parent form

Is there an easy way to center a MessageBox in parent form in .net 2.0

+43
c # winforms messagebox
Nov 13 '09 at 23:02
source share
6 answers

From a commentary on Joel Spolsky 's Blog :

The message box is always focused on the screen. You can provide the owner, but this is only for the Z-order, not for centering. The only way is to use Win32 hooks and center it yourself. You can find the code that does this online if you are looking for it.

It is much easier to just write your own message box class and add centering functions. Then you can also add default headers, "Don't show again," and make them modeless.

"Win32 hooks" probably refers to the use of SetWindowsHookEx , as shown in this example .

+32
Nov 13 '09 at 23:06
source share

I really needed this in C # and found the MessageBox C # Center

Here is a well formatted version

 using System; using System.Windows.Forms; using System.Text; using System.Drawing; using System.Runtime.InteropServices; public class MessageBoxEx { private static IWin32Window _owner; private static HookProc _hookProc; private static IntPtr _hHook; public static DialogResult Show(string text) { Initialize(); return MessageBox.Show(text); } public static DialogResult Show(string text, string caption) { Initialize(); return MessageBox.Show(text, caption); } public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) { Initialize(); return MessageBox.Show(text, caption, buttons); } public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { Initialize(); return MessageBox.Show(text, caption, buttons, icon); } public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton) { Initialize(); return MessageBox.Show(text, caption, buttons, icon, defButton); } public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options) { Initialize(); return MessageBox.Show(text, caption, buttons, icon, defButton, options); } public static DialogResult Show(IWin32Window owner, string text) { _owner = owner; Initialize(); return MessageBox.Show(owner, text); } public static DialogResult Show(IWin32Window owner, string text, string caption) { _owner = owner; Initialize(); return MessageBox.Show(owner, text, caption); } public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { _owner = owner; Initialize(); return MessageBox.Show(owner, text, caption, buttons); } public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { _owner = owner; Initialize(); return MessageBox.Show(owner, text, caption, buttons, icon); } public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton) { _owner = owner; Initialize(); return MessageBox.Show(owner, text, caption, buttons, icon, defButton); } public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options) { _owner = owner; Initialize(); return MessageBox.Show(owner, text, caption, buttons, icon, defButton, options); } public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime); public const int WH_CALLWNDPROCRET = 12; public enum CbtHookAction : int { HCBT_MOVESIZE = 0, HCBT_MINMAX = 1, HCBT_QS = 2, HCBT_CREATEWND = 3, HCBT_DESTROYWND = 4, HCBT_ACTIVATE = 5, HCBT_CLICKSKIPPED = 6, HCBT_KEYSKIPPED = 7, HCBT_SYSCOMMAND = 8, HCBT_SETFOCUS = 9 } [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("User32.dll")] public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc); [DllImport("User32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll")] public static extern int UnhookWindowsHookEx(IntPtr idHook); [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength); [DllImport("user32.dll")] public static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [StructLayout(LayoutKind.Sequential)] public struct CWPRETSTRUCT { public IntPtr lResult; public IntPtr lParam; public IntPtr wParam; public uint message; public IntPtr hwnd; } ; static MessageBoxEx() { _hookProc = new HookProc(MessageBoxHookProc); _hHook = IntPtr.Zero; } private static void Initialize() { if (_hHook != IntPtr.Zero) { throw new NotSupportedException("multiple calls are not supported"); } if (_owner != null) { _hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId()); } } private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return CallNextHookEx(_hHook, nCode, wParam, lParam); } CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); IntPtr hook = _hHook; if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE) { try { CenterWindow(msg.hwnd); } finally { UnhookWindowsHookEx(_hHook); _hHook = IntPtr.Zero; } } return CallNextHookEx(hook, nCode, wParam, lParam); } private static void CenterWindow(IntPtr hChildWnd) { Rectangle recChild = new Rectangle(0, 0, 0, 0); bool success = GetWindowRect(hChildWnd, ref recChild); int width = recChild.Width - recChild.X; int height = recChild.Height - recChild.Y; Rectangle recParent = new Rectangle(0, 0, 0, 0); success = GetWindowRect(_owner.Handle, ref recParent); Point ptCenter = new Point(0, 0); ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); Point ptStart = new Point(0, 0); ptStart.X = (ptCenter.X - (width / 2)); ptStart.Y = (ptCenter.Y - (height / 2)); ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X; ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y; int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false); } } 
+62
Aug 17 '10 at 1:59
source share

But why stop at the implementation of MessageBox? Use the following class as follows:

  private void OnFormClosing(object sender, FormClosingEventArgs e) { DialogResult dg; using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box { dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } if (dg == DialogResult.No) { e.Cancel = true; } } 

Code that you can use with everything that displays dialogs, even if they belong to another thread (our application has several user interface threads):

( Here is the updated code that takes into account the working areas of the monitor, so that the dialogue is not centered between the two monitors or partially off the screen. With it you will need enum SetWindowPosFlags , which is lower)

 public class DialogCenteringService : IDisposable { private readonly IWin32Window owner; private readonly HookProc hookProc; private readonly IntPtr hHook = IntPtr.Zero; public DialogCenteringService(IWin32Window owner) { if (owner == null) throw new ArgumentNullException("owner"); this.owner = owner; hookProc = DialogHookProc; hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId()); } private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return CallNextHookEx(hHook, nCode, wParam, lParam); } CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); IntPtr hook = hHook; if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE) { try { CenterWindow(msg.hwnd); } finally { UnhookWindowsHookEx(hHook); } } return CallNextHookEx(hook, nCode, wParam, lParam); } public void Dispose() { UnhookWindowsHookEx(hHook); } private void CenterWindow(IntPtr hChildWnd) { Rectangle recChild = new Rectangle(0, 0, 0, 0); bool success = GetWindowRect(hChildWnd, ref recChild); if (!success) { return; } int width = recChild.Width - recChild.X; int height = recChild.Height - recChild.Y; Rectangle recParent = new Rectangle(0, 0, 0, 0); success = GetWindowRect(owner.Handle, ref recParent); if (!success) { return; } Point ptCenter = new Point(0, 0); ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); Point ptStart = new Point(0, 0); ptStart.X = (ptCenter.X - (width / 2)); ptStart.Y = (ptCenter.Y - (height / 2)); //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false); Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER)); } // some p/invoke // ReSharper disable InconsistentNaming public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime); private const int WH_CALLWNDPROCRET = 12; // ReSharper disable EnumUnderlyingTypeIsInt private enum CbtHookAction : int // ReSharper restore EnumUnderlyingTypeIsInt { // ReSharper disable UnusedMember.Local HCBT_MOVESIZE = 0, HCBT_MINMAX = 1, HCBT_QS = 2, HCBT_CREATEWND = 3, HCBT_DESTROYWND = 4, HCBT_ACTIVATE = 5, HCBT_CLICKSKIPPED = 6, HCBT_KEYSKIPPED = 7, HCBT_SYSCOMMAND = 8, HCBT_SETFOCUS = 9 // ReSharper restore UnusedMember.Local } [DllImport("kernel32.dll")] static extern int GetCurrentThreadId(); [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags); [DllImport("User32.dll")] public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc); [DllImport("User32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll")] public static extern int UnhookWindowsHookEx(IntPtr idHook); [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength); [DllImport("user32.dll")] public static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [StructLayout(LayoutKind.Sequential)] public struct CWPRETSTRUCT { public IntPtr lResult; public IntPtr lParam; public IntPtr wParam; public uint message; public IntPtr hwnd; }; // ReSharper restore InconsistentNaming } [Flags] public enum SetWindowPosFlags : uint { // ReSharper disable InconsistentNaming /// <summary> /// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. /// </summary> SWP_ASYNCWINDOWPOS = 0x4000, /// <summary> /// Prevents generation of the WM_SYNCPAINT message. /// </summary> SWP_DEFERERASE = 0x2000, /// <summary> /// Draws a frame (defined in the window class description) around the window. /// </summary> SWP_DRAWFRAME = 0x0020, /// <summary> /// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window size is being changed. /// </summary> SWP_FRAMECHANGED = 0x0020, /// <summary> /// Hides the window. /// </summary> SWP_HIDEWINDOW = 0x0080, /// <summary> /// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter). /// </summary> SWP_NOACTIVATE = 0x0010, /// <summary> /// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned. /// </summary> SWP_NOCOPYBITS = 0x0100, /// <summary> /// Retains the current position (ignores X and Y parameters). /// </summary> SWP_NOMOVE = 0x0002, /// <summary> /// Does not change the owner window position in the Z order. /// </summary> SWP_NOOWNERZORDER = 0x0200, /// <summary> /// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing. /// </summary> SWP_NOREDRAW = 0x0008, /// <summary> /// Same as the SWP_NOOWNERZORDER flag. /// </summary> SWP_NOREPOSITION = 0x0200, /// <summary> /// Prevents the window from receiving the WM_WINDOWPOSCHANGING message. /// </summary> SWP_NOSENDCHANGING = 0x0400, /// <summary> /// Retains the current size (ignores the cx and cy parameters). /// </summary> SWP_NOSIZE = 0x0001, /// <summary> /// Retains the current Z order (ignores the hWndInsertAfter parameter). /// </summary> SWP_NOZORDER = 0x0004, /// <summary> /// Displays the window. /// </summary> SWP_SHOWWINDOW = 0x0040, // ReSharper restore InconsistentNaming } hChildWnd, (IntPtr) public class DialogCenteringService : IDisposable { private readonly IWin32Window owner; private readonly HookProc hookProc; private readonly IntPtr hHook = IntPtr.Zero; public DialogCenteringService(IWin32Window owner) { if (owner == null) throw new ArgumentNullException("owner"); this.owner = owner; hookProc = DialogHookProc; hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId()); } private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return CallNextHookEx(hHook, nCode, wParam, lParam); } CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); IntPtr hook = hHook; if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE) { try { CenterWindow(msg.hwnd); } finally { UnhookWindowsHookEx(hHook); } } return CallNextHookEx(hook, nCode, wParam, lParam); } public void Dispose() { UnhookWindowsHookEx(hHook); } private void CenterWindow(IntPtr hChildWnd) { Rectangle recChild = new Rectangle(0, 0, 0, 0); bool success = GetWindowRect(hChildWnd, ref recChild); if (!success) { return; } int width = recChild.Width - recChild.X; int height = recChild.Height - recChild.Y; Rectangle recParent = new Rectangle(0, 0, 0, 0); success = GetWindowRect(owner.Handle, ref recParent); if (!success) { return; } Point ptCenter = new Point(0, 0); ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); Point ptStart = new Point(0, 0); ptStart.X = (ptCenter.X - (width / 2)); ptStart.Y = (ptCenter.Y - (height / 2)); //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false); Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER)); } // some p/invoke // ReSharper disable InconsistentNaming public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime); private const int WH_CALLWNDPROCRET = 12; // ReSharper disable EnumUnderlyingTypeIsInt private enum CbtHookAction : int // ReSharper restore EnumUnderlyingTypeIsInt { // ReSharper disable UnusedMember.Local HCBT_MOVESIZE = 0, HCBT_MINMAX = 1, HCBT_QS = 2, HCBT_CREATEWND = 3, HCBT_DESTROYWND = 4, HCBT_ACTIVATE = 5, HCBT_CLICKSKIPPED = 6, HCBT_KEYSKIPPED = 7, HCBT_SYSCOMMAND = 8, HCBT_SETFOCUS = 9 // ReSharper restore UnusedMember.Local } [DllImport("kernel32.dll")] static extern int GetCurrentThreadId(); [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags); [DllImport("User32.dll")] public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc); [DllImport("User32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll")] public static extern int UnhookWindowsHookEx(IntPtr idHook); [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength); [DllImport("user32.dll")] public static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [StructLayout(LayoutKind.Sequential)] public struct CWPRETSTRUCT { public IntPtr lResult; public IntPtr lParam; public IntPtr wParam; public uint message; public IntPtr hwnd; }; // ReSharper restore InconsistentNaming } [Flags] public enum SetWindowPosFlags : uint { // ReSharper disable InconsistentNaming /// <summary> /// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. /// </summary> SWP_ASYNCWINDOWPOS = 0x4000, /// <summary> /// Prevents generation of the WM_SYNCPAINT message. /// </summary> SWP_DEFERERASE = 0x2000, /// <summary> /// Draws a frame (defined in the window class description) around the window. /// </summary> SWP_DRAWFRAME = 0x0020, /// <summary> /// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window size is being changed. /// </summary> SWP_FRAMECHANGED = 0x0020, /// <summary> /// Hides the window. /// </summary> SWP_HIDEWINDOW = 0x0080, /// <summary> /// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter). /// </summary> SWP_NOACTIVATE = 0x0010, /// <summary> /// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned. /// </summary> SWP_NOCOPYBITS = 0x0100, /// <summary> /// Retains the current position (ignores X and Y parameters). /// </summary> SWP_NOMOVE = 0x0002, /// <summary> /// Does not change the owner window position in the Z order. /// </summary> SWP_NOOWNERZORDER = 0x0200, /// <summary> /// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing. /// </summary> SWP_NOREDRAW = 0x0008, /// <summary> /// Same as the SWP_NOOWNERZORDER flag. /// </summary> SWP_NOREPOSITION = 0x0200, /// <summary> /// Prevents the window from receiving the WM_WINDOWPOSCHANGING message. /// </summary> SWP_NOSENDCHANGING = 0x0400, /// <summary> /// Retains the current size (ignores the cx and cy parameters). /// </summary> SWP_NOSIZE = 0x0001, /// <summary> /// Retains the current Z order (ignores the hWndInsertAfter parameter). /// </summary> SWP_NOZORDER = 0x0004, /// <summary> /// Displays the window. /// </summary> SWP_SHOWWINDOW = 0x0040, // ReSharper restore InconsistentNaming } , SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER public class DialogCenteringService : IDisposable { private readonly IWin32Window owner; private readonly HookProc hookProc; private readonly IntPtr hHook = IntPtr.Zero; public DialogCenteringService(IWin32Window owner) { if (owner == null) throw new ArgumentNullException("owner"); this.owner = owner; hookProc = DialogHookProc; hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId()); } private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return CallNextHookEx(hHook, nCode, wParam, lParam); } CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); IntPtr hook = hHook; if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE) { try { CenterWindow(msg.hwnd); } finally { UnhookWindowsHookEx(hHook); } } return CallNextHookEx(hook, nCode, wParam, lParam); } public void Dispose() { UnhookWindowsHookEx(hHook); } private void CenterWindow(IntPtr hChildWnd) { Rectangle recChild = new Rectangle(0, 0, 0, 0); bool success = GetWindowRect(hChildWnd, ref recChild); if (!success) { return; } int width = recChild.Width - recChild.X; int height = recChild.Height - recChild.Y; Rectangle recParent = new Rectangle(0, 0, 0, 0); success = GetWindowRect(owner.Handle, ref recParent); if (!success) { return; } Point ptCenter = new Point(0, 0); ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); Point ptStart = new Point(0, 0); ptStart.X = (ptCenter.X - (width / 2)); ptStart.Y = (ptCenter.Y - (height / 2)); //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false); Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER)); } // some p/invoke // ReSharper disable InconsistentNaming public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime); private const int WH_CALLWNDPROCRET = 12; // ReSharper disable EnumUnderlyingTypeIsInt private enum CbtHookAction : int // ReSharper restore EnumUnderlyingTypeIsInt { // ReSharper disable UnusedMember.Local HCBT_MOVESIZE = 0, HCBT_MINMAX = 1, HCBT_QS = 2, HCBT_CREATEWND = 3, HCBT_DESTROYWND = 4, HCBT_ACTIVATE = 5, HCBT_CLICKSKIPPED = 6, HCBT_KEYSKIPPED = 7, HCBT_SYSCOMMAND = 8, HCBT_SETFOCUS = 9 // ReSharper restore UnusedMember.Local } [DllImport("kernel32.dll")] static extern int GetCurrentThreadId(); [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags); [DllImport("User32.dll")] public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc); [DllImport("User32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll")] public static extern int UnhookWindowsHookEx(IntPtr idHook); [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength); [DllImport("user32.dll")] public static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [StructLayout(LayoutKind.Sequential)] public struct CWPRETSTRUCT { public IntPtr lResult; public IntPtr lParam; public IntPtr wParam; public uint message; public IntPtr hwnd; }; // ReSharper restore InconsistentNaming } [Flags] public enum SetWindowPosFlags : uint { // ReSharper disable InconsistentNaming /// <summary> /// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. /// </summary> SWP_ASYNCWINDOWPOS = 0x4000, /// <summary> /// Prevents generation of the WM_SYNCPAINT message. /// </summary> SWP_DEFERERASE = 0x2000, /// <summary> /// Draws a frame (defined in the window class description) around the window. /// </summary> SWP_DRAWFRAME = 0x0020, /// <summary> /// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window size is being changed. /// </summary> SWP_FRAMECHANGED = 0x0020, /// <summary> /// Hides the window. /// </summary> SWP_HIDEWINDOW = 0x0080, /// <summary> /// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter). /// </summary> SWP_NOACTIVATE = 0x0010, /// <summary> /// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned. /// </summary> SWP_NOCOPYBITS = 0x0100, /// <summary> /// Retains the current position (ignores X and Y parameters). /// </summary> SWP_NOMOVE = 0x0002, /// <summary> /// Does not change the owner window position in the Z order. /// </summary> SWP_NOOWNERZORDER = 0x0200, /// <summary> /// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing. /// </summary> SWP_NOREDRAW = 0x0008, /// <summary> /// Same as the SWP_NOOWNERZORDER flag. /// </summary> SWP_NOREPOSITION = 0x0200, /// <summary> /// Prevents the window from receiving the WM_WINDOWPOSCHANGING message. /// </summary> SWP_NOSENDCHANGING = 0x0400, /// <summary> /// Retains the current size (ignores the cx and cy parameters). /// </summary> SWP_NOSIZE = 0x0001, /// <summary> /// Retains the current Z order (ignores the hWndInsertAfter parameter). /// </summary> SWP_NOZORDER = 0x0004, /// <summary> /// Displays the window. /// </summary> SWP_SHOWWINDOW = 0x0040, // ReSharper restore InconsistentNaming } 
+8
Mar 12 '13 at 18:45
source share

Of course, using your own panel or form would be the easiest way if the code were a bit heavier in the background (designer). It gives you all control in terms of centering and manipulation without writing all this custom code.

+5
Aug 07 '12 at 7:40
source share

I slightly modified the previous answer and compiled a WPF version of MessageBoxEx. This code works fine for me. Feel free to report code issues.

Note: I use GeneralObjects.MainWindowInstance in ctor to initialize a class with my main window, but in fact I use it for any window because of its cache for the last parent window. Therefore, you can simply delete everything from ctor.

 public class MessageBoxEx { private static HwndSource source_ = null; private static HwndSourceHook hook_ = null; static MessageBoxEx() { try { // create cached createHwndSource_(GeneralObjects.MainWindowInstance); hook_ = new HwndSourceHook(HwndSourceHook); } finally { if (null == source_ || null == hook_) { source_ = null; hook_ = null; } } } private static void createHwndSource_(Window owner) { source_ = (HwndSource)PresentationSource.FromVisual(owner); } public static void Initialize_(Window owner = null) { try { if (null != owner) { if(source_.RootVisual != owner) { createHwndSource_(owner); } } } finally { if (null == source_ || null == hook_) { source_ = null; hook_ = null; } } if (null != source_ && null != hook_) { source_.AddHook(hook_); } } public static MessageBoxResult Show(string messageBoxText) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText); } public static MessageBoxResult Show(string messageBoxText, string caption) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText, caption); } public static MessageBoxResult Show(Window owner, string messageBoxText) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText); } public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText, caption, button); } public static MessageBoxResult Show(Window owner, string messageBoxText, string caption) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText, caption); } public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon); } public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button); } public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult); } public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon); } public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options) { Initialize_(); return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options); } public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult); } public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options) { Initialize_(owner); return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options); } private enum WM : int { WM_ACTIVATE = 0x0006 } private static IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if ((int)WM.WM_ACTIVATE == msg && source_.Handle == hwnd && 0 == (int)wParam) { try { CenterWindow(lParam); } finally { // remove hook at once after moved message box window. source_.RemoveHook(hook_); } } return IntPtr.Zero; } [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); private static void CenterWindow(IntPtr hChildWnd) { System.Drawing.Rectangle recChild = new System.Drawing.Rectangle(0, 0, 0, 0); bool success = GetWindowRect(hChildWnd, ref recChild); int width = recChild.Width - recChild.X; int height = recChild.Height - recChild.Y; System.Drawing.Rectangle recParent = new System.Drawing.Rectangle(0, 0, 0, 0); success = GetWindowRect(source_.Handle, ref recParent); System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0); ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); System.Drawing.Point ptStart = new System.Drawing.Point(0, 0); ptStart.X = (ptCenter.X - (width / 2)); ptStart.Y = (ptCenter.Y - (height / 2)); // I have commented this code because of I have 2 monitors // so If application located at 1st monitor // message box can appear at second one. /* ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X; ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y; */ int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false); } } 
+5
Aug 15 '12 at 10:30
source share

Try it, it's simple enough to justify the time ...

This is for the Win32 API written in C. Translate it as you need ...

 case WM_NOTIFY:{ HWND X=FindWindow("#32770",NULL); if(GetParent(X)==H_frame){int Px,Py,Sx,Sy; RECT R1,R2; GetWindowRect(hwnd,&R1); GetWindowRect(X,&R2); Sx=R2.right-R2.left,Px=R1.left+(R1.right-R1.left)/2-Sx/2; Sy=R2.bottom-R2.top,Py=R1.top+(R1.bottom-R1.top)/2-Sy/2; MoveWindow(X,Px,Py,Sx,Sy,1); } } break; 

Add this to the WndProc code ... You can set the position as you wish, in which case it is simply centered on the main program window. He will do this for any message box or dialog for opening / saving files and, possibly, some other built-in controls. I'm not sure, but I think you might need to enable COMMCTRL or COMMDLG to use this, at least if you want to open / save dialogs.

I experimented with viewing the notification codes and hwndFrom from NMHDR, and then decided that it was just as efficient and much easier, not. If you really want to be very specific, tell FindWindow to find the unique signature (title) that you specify in the window that you want to find.

This works before the message box is displayed, so if you set a global flag to indicate when the action is executed by your code and find a unique title, you will make sure that the actions you take will occur only once ( there will probably be several notifications). I did not study this in detail, but I managed to get CreateWindow to place the edit box in the message dialog. It looked out of place, like rat ears grafted onto the spine of a cloned pig, but it works. Doing things this way can be a lot easier than being able to collapse your own.

Crow

EDIT: A small correction to ensure that the right window is processed. Make sure that the parent handles are consistent throughout and this should work fine. This is for me, even with two instances of the same program ...

+4
May 25 '12 at 20:00
source share



All Articles