Center of Parent

A message box is always centered on the screen.
It is possible to display a message box in the middle of the Application window.
This approach retrieves the position and size of the application window and then moves the message box window.
Two Windows API functions are used in this solutions.

public struct structure_RECT 
   public int Left;
   public int Top;
   public int Right;
   public int Bottom;

public extern bool GetWindowRect(System.IntPtr hWnd, ref structure_RECT rect)

public extern IntPtr FindWindow(string lpClassName, string lpWindowName)




public static void MessageBox_CenterApplication( 
    string caption)
        Constants.Structure_RECT oRect;
        System.IntPtr ohandle;
        System.Windows.Forms.NativeWindow nativeWindow;

        oRect = new Constants.Structure_RECT();
        ohandle = Code.Method_HandleGet(Globals.ThisAddIn.Application);
        nativeWindow = new System.Windows.Forms.NativeWindow();
        Constants.GetWindowRect(ohandle, ref oRect);

        int ExcelWindow_CenterX = oRect.Left + (oRect.Right - oRect.Left) / 2;
        int ExcelWindow_CenterY = oRect.Top + (oRect.Bottom - oRect.Top) / 2;

        Constants.gTHREAD_MESSAGEBOXCENTER = new System.Threading.Thread(() =>
            Constants.Structure_RECT oRect2;
            System.IntPtr ohandle2;

            oRect2 = new Constants.Structure_RECT();

            while ((ohandle2 = Constants.FindWindow(System.IntPtr.Zero, caption)) == System.IntPtr.Zero) ;

            Constants.GetWindowRect(ohandle2, ref oRect2);

            int Msgbox_Left = ExcelWindow_CenterX - (int)(oRect2.Right - oRect2.Left) / 2;
            int Msgbox_Top = ExcelWindow_CenterY - (int)(oRect2.Bottom - oRect2.Top) / 2;

            Constants.MoveWindow(ohandle2, Msgbox_Left, Msgbox_Top,
                oRect2.Right - oRect2.Left,
                oRect2.Bottom - oRect2.Top, true);

        //Must include this after the MessageBox.Show
    catch (System.Exception ex)
        ExceptionHandling.MessageShow(System.Reflection.MethodBase.GetCurrentMethod(), ex);

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext