自定义消息框 WPF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21768186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:50:40  来源:igfitidea点击:

Custom MessageBox WPF

.netwpfmessagebox

提问by paparazzo

From this link I would like to display a MessageBox like the one

从这个链接,我想显示一个像这样的 MessageBox

UI

用户界面

Formatting will erase all the data on this disk.

格式化将清除此磁盘上的所有数据。

On that the named the button Format I am not finding that as a MessageBox.
How is that done?
Is this just a custom modal Window?

在那个命名的按钮格式上,我没有发现它是一个 MessageBox。
这是怎么做的?
这只是一个自定义模态窗口吗?

This seems close but does not rename a button

这似乎很接近,但不会重命名按钮

MessageBox.Show

消息框显示

I know you are not supposed to use tags in the title but there is Custom MessageBox title already but it deals with Forms.

我知道你不应该在标题中使用标签,但已经有自定义 MessageBox 标题,但它处理表单。

回答by Tony

You can use WPF Toolkit custom MessageBox
then change the OkButtonContent
to set the content of the OK button.

您可以使用 WPF Toolkit 自定义 MessageBox
然后更改OkButtonContent
以设置 OK 按钮的内容。

https://wpftoolkit.codeplex.com/wikipage?title=MessageBox

https://wpftoolkit.codeplex.com/wikipage?title=MessageBox

回答by Toan Nguyen

To achieve what you want:

为了实现你想要的:

  1. Create a custom window control inheriting from Window
  1. 创建一个继承自 Window 的自定义窗口控件

For instance

例如

public partial class CustomMessageBoxWindow : Window {}

公共部分类 CustomMessageBoxWindow : Window {}

  1. Design the layout for that window. You will need a label for the title. An image on the left, and a label to display the message. In addtion, you may need to add various buttons like Yes/No, Ok/Cancel.

  2. Expose what you have done by using another class. Let's say CustomMessageBox.

  1. 设计该窗口的布局。您将需要标题的标签。左侧的图像和用于显示消息的标签。此外,您可能需要添加各种按钮,如是/否、确定/取消。

  2. 使用另一个类公开你所做的事情。让我们说 CustomMessageBox。

This linkprovides an implementation, that you may take a look at.

链接提供了一个实现,您可以查看一下。

回答by Rashad Annara

Try this code,

试试这个代码,

public class MsgBox : Form
{
    private const int CS_DROPSHADOW = 0x00020000;
    private static MsgBox _msgBox;
    private Panel _plHeader = new Panel();
    private Panel _plFooter = new Panel();
    private Panel _plIcon = new Panel();
    private PictureBox _picIcon = new PictureBox();
    private FlowLayoutPanel _flpButtons = new FlowLayoutPanel();
    private Label _lblTitle;
    private Label _lblMessage;
    private List<Button> _buttonCollection = new List<Button>();
    private static DialogResult _buttonResult = new DialogResult();
    private static Timer _timer;
    private static Point lastMousePos;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern bool MessageBeep(uint type);

    private MsgBox()
    {
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.BackColor = Color.FromArgb(0, 50, 90);
        this.StartPosition = FormStartPosition.CenterScreen;
        this.Padding = new System.Windows.Forms.Padding(3);
        this.Width = 400;

        _lblTitle = new Label();
        _lblTitle.ForeColor = Color.White;
        _lblTitle.Font = new System.Drawing.Font("Segoe UI", 18);
        _lblTitle.Dock = DockStyle.Top;
        _lblTitle.Height = 50;

        _lblMessage = new Label();
        _lblMessage.ForeColor = Color.White;
        _lblMessage.Font = new System.Drawing.Font("Segoe UI", 10);
        _lblMessage.Dock = DockStyle.Fill;

        _flpButtons.FlowDirection = FlowDirection.RightToLeft;
        _flpButtons.Dock = DockStyle.Fill;

        _plHeader.Dock = DockStyle.Fill;
        _plHeader.Padding = new Padding(20);
        _plHeader.Controls.Add(_lblMessage);
        _plHeader.Controls.Add(_lblTitle);

        _plFooter.Dock = DockStyle.Bottom;
        _plFooter.Padding = new Padding(20);
        _plFooter.BackColor = Color.FromArgb(0, 0, 90);
        _plFooter.Height = 80;
        _plFooter.Controls.Add(_flpButtons);

        _picIcon.Width = 32;
        _picIcon.Height = 32;
        _picIcon.Location = new Point(30, 50);

        _plIcon.Dock = DockStyle.Left;
        _plIcon.Padding = new Padding(20);
        _plIcon.Width = 70;
        _plIcon.Controls.Add(_picIcon);

        List<Control> controlCollection = new List<Control>();
        controlCollection.Add(this);
        controlCollection.Add(_lblTitle);
        controlCollection.Add(_lblMessage);
        controlCollection.Add(_flpButtons);
        controlCollection.Add(_plHeader);
        controlCollection.Add(_plFooter);
        controlCollection.Add(_plIcon);
        controlCollection.Add(_picIcon);

        foreach (Control control in controlCollection)
        {
            control.MouseDown += MsgBox_MouseDown;
            control.MouseMove += MsgBox_MouseMove;
        }

        this.Controls.Add(_plHeader);
        this.Controls.Add(_plIcon);
        this.Controls.Add(_plFooter);
    }

    private static void MsgBox_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            lastMousePos = new Point(e.X, e.Y);
        }
    }


    private static void MsgBox_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            _msgBox.Left += e.X - lastMousePos.X;
            _msgBox.Top += e.Y - lastMousePos.Y;
        }
    }

    public static DialogResult Show(string message)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;

        MsgBox.InitButtons(Buttons.OK);

        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    public static DialogResult Show(string message, string title)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;
        _msgBox.Size = MsgBox.MessageSize(message);

        MsgBox.InitButtons(Buttons.OK);

        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    public static DialogResult Show(string message, string title, Buttons buttons)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;
        _msgBox._plIcon.Hide();

        MsgBox.InitButtons(buttons);

        _msgBox.Size = MsgBox.MessageSize(message);
        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    public static DialogResult Show(string message, string title, Buttons buttons, Icon icon)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;

        MsgBox.InitButtons(buttons);
        MsgBox.InitIcon(icon);

        _msgBox.Size = MsgBox.MessageSize(message);
        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    public static DialogResult Show(string message, string title, Buttons buttons, Icon icon, AnimateStyle style)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;
        _msgBox.Height = 0;

        MsgBox.InitButtons(buttons);
        MsgBox.InitIcon(icon);

        _timer = new Timer();
        Size formSize = MsgBox.MessageSize(message);

        switch (style)
        {
            case MsgBox.AnimateStyle.SlideDown:
                _msgBox.Size = new Size(formSize.Width, 0);
                _timer.Interval = 1;
                _timer.Tag = new AnimateMsgBox(formSize, style);
                break;

            case MsgBox.AnimateStyle.FadeIn:
                _msgBox.Size = formSize;
                _msgBox.Opacity = 0;
                _timer.Interval = 20;
                _timer.Tag = new AnimateMsgBox(formSize, style);
                break;

            case MsgBox.AnimateStyle.ZoomIn:
                _msgBox.Size = new Size(formSize.Width + 100, formSize.Height + 100);
                _timer.Tag = new AnimateMsgBox(formSize, style);
                _timer.Interval = 1;
                break;
        }

        _timer.Tick += timer_Tick;
        _timer.Start();

        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    static void timer_Tick(object sender, EventArgs e)
    {
        Timer timer = (Timer)sender;
        AnimateMsgBox animate = (AnimateMsgBox)timer.Tag;

        switch (animate.Style)
        {
            case MsgBox.AnimateStyle.SlideDown:
                if (_msgBox.Height < animate.FormSize.Height)
                {
                    _msgBox.Height += 17;
                    _msgBox.Invalidate();
                }
                else
                {
                    _timer.Stop();
                    _timer.Dispose();
                }
                break;

            case MsgBox.AnimateStyle.FadeIn:
                if (_msgBox.Opacity < 1)
                {
                    _msgBox.Opacity += 0.1;
                    _msgBox.Invalidate();
                }
                else
                {
                    _timer.Stop();
                    _timer.Dispose();
                }
                break;

            case MsgBox.AnimateStyle.ZoomIn:
                if (_msgBox.Width > animate.FormSize.Width)
                {
                    _msgBox.Width -= 17;
                    _msgBox.Invalidate();
                }
                if (_msgBox.Height > animate.FormSize.Height)
                {
                    _msgBox.Height -= 17;
                    _msgBox.Invalidate();
                }
                break;
        }
    }

    private static void InitButtons(Buttons buttons)
    {
        switch (buttons)
        {
            case MsgBox.Buttons.AbortRetryIgnore:
                _msgBox.InitAbortRetryIgnoreButtons();
                break;

            case MsgBox.Buttons.OK:
                _msgBox.InitOKButton();
                break;

            case MsgBox.Buttons.OKCancel:
                _msgBox.InitOKCancelButtons();
                break;

            case MsgBox.Buttons.RetryCancel:
                _msgBox.InitRetryCancelButtons();
                break;

            case MsgBox.Buttons.YesNo:
                _msgBox.InitYesNoButtons();
                break;

            case MsgBox.Buttons.YesNoCancel:
                _msgBox.InitYesNoCancelButtons();
                break;
        }

        foreach (Button btn in _msgBox._buttonCollection)
        {
            btn.ForeColor = Color.FromArgb(170, 170, 170);
            btn.Font = new System.Drawing.Font("Segoe UI", 8);
            btn.Padding = new Padding(3);
            btn.FlatStyle = FlatStyle.Flat;
            btn.Height = 30;
            btn.FlatAppearance.BorderColor = Color.FromArgb(99, 99, 98);

            _msgBox._flpButtons.Controls.Add(btn);
        }
    }

    private static void InitIcon(Icon icon)
    {
        switch (icon)
        {
            case MsgBox.Icon.Application:
                _msgBox._picIcon.Image = SystemIcons.Application.ToBitmap();
                break;

            case MsgBox.Icon.Exclamation:
                _msgBox._picIcon.Image = SystemIcons.Exclamation.ToBitmap();
                break;

            case MsgBox.Icon.Error:
                _msgBox._picIcon.Image = SystemIcons.Error.ToBitmap();
                break;

            case MsgBox.Icon.Info:
                _msgBox._picIcon.Image = SystemIcons.Information.ToBitmap();
                break;

            case MsgBox.Icon.Question:
                _msgBox._picIcon.Image = SystemIcons.Question.ToBitmap();
                break;

            case MsgBox.Icon.Shield:
                _msgBox._picIcon.Image = SystemIcons.Shield.ToBitmap();
                break;

            case MsgBox.Icon.Warning:
                _msgBox._picIcon.Image = SystemIcons.Warning.ToBitmap();
                break;
        }
    }

    private void InitAbortRetryIgnoreButtons()
    {
        Button btnAbort = new Button();
        btnAbort.Text = "Abort";
        btnAbort.Click += ButtonClick;

        Button btnRetry = new Button();
        btnRetry.Text = "Retry";
        btnRetry.Click += ButtonClick;

        Button btnIgnore = new Button();
        btnIgnore.Text = "Ignore";
        btnIgnore.Click += ButtonClick;

        this._buttonCollection.Add(btnAbort);
        this._buttonCollection.Add(btnRetry);
        this._buttonCollection.Add(btnIgnore);
    }

    private void InitOKButton()
    {
        Button btnOK = new Button();
        btnOK.Text = "OK";
        btnOK.Click += ButtonClick;

        this._buttonCollection.Add(btnOK);
    }

    private void InitOKCancelButtons()
    {
        Button btnOK = new Button();
        btnOK.Text = "OK";
        btnOK.Click += ButtonClick;

        Button btnCancel = new Button();
        btnCancel.Text = "Cancel";
        btnCancel.Click += ButtonClick;


        this._buttonCollection.Add(btnOK);
        this._buttonCollection.Add(btnCancel);
    }

    private void InitRetryCancelButtons()
    {
        Button btnRetry = new Button();
        btnRetry.Text = "OK";
        btnRetry.Click += ButtonClick;

        Button btnCancel = new Button();
        btnCancel.Text = "Cancel";
        btnCancel.Click += ButtonClick;


        this._buttonCollection.Add(btnRetry);
        this._buttonCollection.Add(btnCancel);
    }

    private void InitYesNoButtons()
    {
        Button btnYes = new Button();
        btnYes.Text = "Yes";
        btnYes.Click += ButtonClick;

        Button btnNo = new Button();
        btnNo.Text = "No";
        btnNo.Click += ButtonClick;


        this._buttonCollection.Add(btnYes);
        this._buttonCollection.Add(btnNo);
    }

    private void InitYesNoCancelButtons()
    {
        Button btnYes = new Button();
        btnYes.Text = "Abort";
        btnYes.Click += ButtonClick;

        Button btnNo = new Button();
        btnNo.Text = "Retry";
        btnNo.Click += ButtonClick;

        Button btnCancel = new Button();
        btnCancel.Text = "Cancel";
        btnCancel.Click += ButtonClick;

        this._buttonCollection.Add(btnYes);
        this._buttonCollection.Add(btnNo);
        this._buttonCollection.Add(btnCancel);
    }

    private static void ButtonClick(object sender, EventArgs e)
    {
        Button btn = (Button)sender;

        switch (btn.Text)
        {
            case "Abort":
                _buttonResult = DialogResult.Abort;
                break;

            case "Retry":
                _buttonResult = DialogResult.Retry;
                break;

            case "Ignore":
                _buttonResult = DialogResult.Ignore;
                break;

            case "OK":
                _buttonResult = DialogResult.OK;
                break;

            case "Cancel":
                _buttonResult = DialogResult.Cancel;
                break;

            case "Yes":
                _buttonResult = DialogResult.Yes;
                break;

            case "No":
                _buttonResult = DialogResult.No;
                break;
        }

        _msgBox.Dispose();
    }

    private static Size MessageSize(string message)
    {
        Graphics g = _msgBox.CreateGraphics();
        int width = 350;
        int height = 230;

        SizeF size = g.MeasureString(message, new System.Drawing.Font("Segoe UI", 10));

        if (message.Length < 150)
        {
            if ((int)size.Width > 350)
            {
                width = (int)size.Width;
            }
        }
        else
        {
            string[] groups = (from Match m in Regex.Matches(message, ".{1,180}") select m.Value).ToArray();
            int lines = groups.Length + 1;
            width = 700;
            height += (int)(size.Height + 10) * lines;
        }
        return new Size(width, height);
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ClassStyle |= CS_DROPSHADOW;
            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Graphics g = e.Graphics;
        Rectangle rect = new Rectangle(new Point(0, 0), new Size(this.Width - 1, this.Height - 1));
        Pen pen = new Pen(Color.FromArgb(0, 151, 251));

        g.DrawRectangle(pen, rect);
    }

    public enum Buttons
    {
        AbortRetryIgnore = 1,
        OK = 2,
        OKCancel = 3,
        RetryCancel = 4,
        YesNo = 5,
        YesNoCancel = 6
    }

    public enum Icon
    {
        Application = 1,
        Exclamation = 2,
        Error = 3,
        Warning = 4,
        Info = 5,
        Question = 6,
        Shield = 7,
        Search = 8
    }

    public enum AnimateStyle
    {
        SlideDown = 1,
        FadeIn = 2,
        ZoomIn = 3
    }

}

class AnimateMsgBox
{
    public Size FormSize;
    public MsgBox.AnimateStyle Style;

    public AnimateMsgBox(Size formSize, MsgBox.AnimateStyle style)
    {
        this.FormSize = formSize;
        this.Style = style;
    }
}

and you can use this message box in you code like

你可以在你的代码中使用这个消息框

MsgBox.Show("Are you sure you want to close the Application ?", "Confirmation", MsgBox.Buttons.YesNo, MsgBox.Icon.Question, MsgBox.AnimateStyle.FadeIn);

or if you want to check the result, which button is clicked

或者如果你想检查结果,点击哪个按钮

        var result = MsgBox.Show("Are you sure you want to close the Application ?", "Confirmation", MsgBox.Buttons.YesNo, MsgBox.Icon.Question, MsgBox.AnimateStyle.FadeIn);

        if (result == System.Windows.Forms.DialogResult.No)
        {
            ////do whatever you want
        }

your message box will look like this

您的消息框将如下所示

enter image description here

在此处输入图片说明

if you want to change the background color, change here

如果要更改背景颜色,请在此处更改

this.BackColor = Color.FromArgb(0, 50, 90);

and

_plFooter.BackColor = Color.FromArgb(0, 0, 90);

回答by Kevin DiTraglia

There are some overloads on MessageBox.Show that can make that message:

MessageBox.Show 上有一些重载可以生成该消息:

MessageBox.Show("Formatting will erase all data on this disk. \nTo format the disk, click OK.  To quit, click Cancel.", 
     "Format Local Disk (F:)", 
     MessageBoxButton.OKCancel,
     MessageBoxImage.Exclamation);

The MessageBoxButtonenum lets you choose between OK, OKCancel, YesNo, and YesNoCancel. If you want different buttons than that I'm afraid you have to use the advice of the other answers and create your own window.

MessageBoxButton枚举让你选择之间OKOKCancelYesNo,和YesNoCancel。如果您想要不同的按钮,恐怕您必须使用其他答案的建议并创建自己的窗口。