使消息框相对于表单居中

时间:2010-12-04 09:48:42

标签: c# visual-studio winforms messagebox

我拍摄的消息框出现在窗口的中央,但有没有办法让它们出现在窗体的中心。

2 个答案:

答案 0 :(得分:0)

如果您正在谈论标准MessageBox,并且希望它显示在调用它的Form的中心,请尝试This Solution。请注意,您要查看来自" Joe"的答案。而不是标记作为答案。

我已经使用了它,它对我很有用。

答案 1 :(得分:0)

这是我自己的消息框用C#winform,除了中心父窗体的实现,还可以自定义按钮文字和图标。

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);
            }
        }
    }
}