开发者

Centering the messagebox with respect to the form

开发者 https://www.devze.com 2023-01-29 00:42 出处:网络
The messagebox I have taken is appea开发者_运维百科ring in the center of the windows but is there any way to make them appear at the center of the form.If you ARE talking about a standard MessageBox,

The messagebox I have taken is appea开发者_运维百科ring in the center of the windows but is there any way to make them appear at the center of the form.


If you ARE talking about a standard MessageBox, and you want it to show in the center of the Form that calls it, then try This Solution. Note that you want to look at the answer from "Joe" rather than the one marked as the answer.

I've used this and it works great for me.


This is my own message box use C# winform, In addition to the realization of the parent form in the center, can customize the button text and icon.

using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace BluePointLilac.Methods
{
    /// <summary>在窗体居中显示的MessageBox</summary>
    public class MessageBoxEx
    {
        public static DialogResult Show(string text, string caption = null,
            MessageBoxButtons buttons = MessageBoxButtons.OK,
            MessageBoxIcon boxIcon = MessageBoxIcon.None)
        {
            using(MessageBoxForm frm = new MessageBoxForm(text, caption, buttons, boxIcon))
            {
                return frm.ShowDialog();
            }
        }

        public static string Show(string text, string caption,
            string[] buttonTexts, Image boxImaage, bool cancelBox = false)
        {
            using(MessageBoxForm frm = new MessageBoxForm(text, caption, buttonTexts, boxImaage, cancelBox))
            {
                frm.ShowDialog();
                return frm.Tag?.ToString();
            }
        }

        sealed class MessageBoxForm : Form
        {
            private MessageBoxForm(string text, string caption)
            {
                lblText.Text = text;
                this.Text = caption;
                this.Font = SystemFonts.MessageBoxFont;
                this.ShowIcon = this.ShowInTaskbar = false;
                this.MaximizeBox = this.MinimizeBox = false;
                this.FormBorderStyle = FormBorderStyle.FixedSingle;
                this.StartPosition = FormStartPosition.CenterParent;
            }

            public MessageBoxForm(string text, string caption,
                string[] buttonTexts, Image boxImage, bool cancelBox) : this(text, caption)
            {
                this.CancelBox = cancelBox;
                this.InitializeComponents(buttonTexts, boxImage);
                foreach(Button button in flpButtons.Controls)
                {
                    button.Click += (sender, e) =>
                    {
                        this.Tag = button.Text;
                        this.Close();
                    };
                }
            }

            public MessageBoxForm(string text, string caption,
                MessageBoxButtons buttons, MessageBoxIcon boxIcon) : this(text, caption)
            {
                string[] buttonTexts = null;
                Image boxImage = null;
                switch(buttons)
                {
                    case MessageBoxButtons.OK:
                        buttonTexts = new[] { "OK" }; break;
                    case MessageBoxButtons.OKCancel:
                        buttonTexts = new[] { "Cancel", "OK" }; break;
                    case MessageBoxButtons.AbortRetryIgnore:
                        buttonTexts = new[] { "&Ignore", "&Retry", "&Abort" }; break;
                    case MessageBoxButtons.YesNoCancel:
                        buttonTexts = new[] { "Cancel", "&No", "&Yes" }; break;
                    case MessageBoxButtons.YesNo:
                        buttonTexts = new[] { "&No", "&Yes" }; break;
                    case MessageBoxButtons.RetryCancel:
                        buttonTexts = new[] { "Cancel", "&Retry" }; break;
                }
                switch(boxIcon)
                {
                    case MessageBoxIcon.Question:
                        boxImage = SystemIcons.Question.ToBitmap(); break;
                    case MessageBoxIcon.Error:
                        boxImage = SystemIcons.Error.ToBitmap(); break;
                    case MessageBoxIcon.Warning:
                        boxImage = SystemIcons.Warning.ToBitmap(); break;
                    case MessageBoxIcon.Information:
                        boxImage = SystemIcons.Information.ToBitmap(); break;
                }
                this.CancelBox = !buttonTexts.Contains("Cancel");
                this.InitializeComponents(buttonTexts, boxImage);
                foreach(Button button in flpButtons.Controls)
                {
                    button.Click += (sender, e) =>
                    {
                        switch(button.Text)
                        {
                            case "OK":
                                this.DialogResult = DialogResult.OK; break;
                            case "Cancel":
                                this.DialogResult = DialogResult.Cancel; break;
                            case "&Yes":
                                this.DialogResult = DialogResult.Yes; break;
                            case "&No":
                                this.DialogResult = DialogResult.No; break;
                            case "&Abort":
                                this.DialogResult = DialogResult.Abort; break;
                            case "&Retry":
                                this.DialogResult = DialogResult.Retry; break;
                            case "&Ignore":
                                this.DialogResult = DialogResult.Ignore; break;
                        }
                    };
                }
            }

            private void InitializeComponents(string[] buttonTexts, Image boxImage)
            {
                int w1 = 0;
                Size buttonSize = new Size(75, 27);
                for(int i = 0; i < buttonTexts.Length; i++)
                {
                    Button button = new Button
                    {
                        Margin = new Padding(0, 12, 12, 12),
                        Parent = flpButtons,
                        AutoSize = true,
                        Text = buttonTexts[i],
                    };
                    button.Width = Math.Max(buttonSize.Width, button.Width);
                    button.Height = Math.Max(buttonSize.Height, button.Height);
                    buttonSize = button.Size;
                    w1 += button.Width + button.Margin.Horizontal;
                }
                picIcon.Image = boxImage;
                if(boxImage == null)
                {
                    picIcon.Visible = false;
                    lblText.Left = 35;
                }
                pnlInfo.Controls.AddRange(new Control[] { picIcon, lblText });
                this.Controls.AddRange(new Control[] { pnlInfo, flpButtons });
                pnlInfo.Height = lblText.Height + lblText.Top * 2;
                int w2 = lblText.Right + picIcon.Left;
                int w = Math.Max(w1, w2);
                int h = pnlInfo.Height + flpButtons.Height;
                this.ClientSize = new Size(w, h);
            }

            readonly FlowLayoutPanel flpButtons = new FlowLayoutPanel
            {
                Padding = new Padding(0, 0, 12, 0),
                FlowDirection = FlowDirection.RightToLeft,
                BackColor = default,
                Dock = DockStyle.Bottom,
                Height = 50
            };
            readonly Panel pnlInfo = new Panel
            {
                BackColor = Color.White,
                Dock = DockStyle.Top,
            };
            readonly PictureBox picIcon = new PictureBox
            {
                SizeMode = PictureBoxSizeMode.AutoSize,
                Location = new Point(30, 30)
            };
            readonly Label lblText = new Label
            {
                Location = new Point(67, 32),
                AutoSize = true,
            };

            readonly bool CancelBox = false;

            protected override CreateParams CreateParams
            {
                get
                {
                    const int CP_NOCLOSE_BUTTON = 0x200;
                    CreateParams cp = base.CreateParams;
                    if(CancelBox) cp.ClassStyle |= CP_NOCLOSE_BUTTON; //禁用关闭按钮
                    return cp;
                }
            }

            protected override bool ProcessDialogKey(Keys keyData)
            {
                if(ModifierKeys == Keys.None)
                {
                    if(!CancelBox && keyData == Keys.Escape)
                    {
                        this.DialogResult = DialogResult.Cancel; //ESC键关闭窗体并返回“取消”
                        return true;
                    }
                }
                return base.ProcessDialogKey(keyData);
            }

            protected override void OnLoad(EventArgs e)
            {
                this.Owner = Form.ActiveForm;
                if(this.Owner == null) this.StartPosition = FormStartPosition.CenterScreen;
                base.OnLoad(e);
            }
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消