简体   繁体   中英

Different Colors for a String to display in C# MessageBox

Is it possible to have different colors for a message in MessageBox in C#?

Example: Let the string be "Placeholder Text" Can we display "Placeholder" in black and "Text" in red in a C# MessageBox?

As I know you cant change that in MessageBox because it depends on how your windows look

but you can create a new Form where you would do it with this your shown Form will be only thing that can user manipulate until its closed:

Form2 form2 = new Form2();
        form2.StartPosition = FormStartPosition.CenterScreen; //with this you can be sure that it will always open in the middle of the screen
        form2.ShowDialog();

then you add from how I understand your question label and just write:

Label1.ForeColor = Color.Red;
Label1.BackColor = Color.Black;

I hope it will help and I hope I did understand your question

I have a custom MessageBox class that you can modify changing the Label for a RichTextBox as @Caius Jard comment.

This is the.designer file of the form:

partial class MessageBoxForm
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.pictureBox = new System.Windows.Forms.PictureBox();
        this.label = new System.Windows.Forms.Label();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.button3 = new System.Windows.Forms.Button();
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
        this.SuspendLayout();
        // 
        // pictureBox
        // 
        this.pictureBox.Location = new System.Drawing.Point(24, 32);
        this.pictureBox.Name = "pictureBox";
        this.pictureBox.Size = new System.Drawing.Size(52, 52);
        this.pictureBox.TabIndex = 0;
        this.pictureBox.TabStop = false;
        // 
        // label
        // 
        this.label.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.label.Location = new System.Drawing.Point(84, 28);
        this.label.Name = "label";
        this.label.Size = new System.Drawing.Size(433, 56);
        this.label.TabIndex = 1;
        this.label.Text = "Text";
        // 
        // button1
        // 
        this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
        this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
        this.button1.Location = new System.Drawing.Point(12, 95);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 28);
        this.button1.TabIndex = 2;
        this.button1.Text = "&OK";
        this.button1.UseVisualStyleBackColor = true;
        // 
        // button2
        // 
        this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
        this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        this.button2.Location = new System.Drawing.Point(93, 95);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(75, 28);
        this.button2.TabIndex = 3;
        this.button2.Text = "&Cancel";
        this.button2.UseVisualStyleBackColor = true;
        this.button2.Visible = false;
        // 
        // button3
        // 
        this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
        this.button3.Location = new System.Drawing.Point(174, 95);
        this.button3.Name = "button3";
        this.button3.Size = new System.Drawing.Size(75, 28);
        this.button3.TabIndex = 4;
        this.button3.Text = "button3";
        this.button3.UseVisualStyleBackColor = true;
        this.button3.Visible = false;
        // 
        // MessageBoxForm
        // 
        this.AcceptButton = this.button1;
        this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.CancelButton = this.button2;
        this.ClientSize = new System.Drawing.Size(529, 135);
        this.Controls.Add(this.button3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.Controls.Add(this.label);
        this.Controls.Add(this.pictureBox);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "MessageBoxForm";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
        this.Text = "Text";
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.PictureBox pictureBox;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Button button3;
}

And the code:

public partial class MessageBoxForm : Form
{
    public static Func<DialogResult, string> TranslateButtonText { get; set; }
    
    public MessageBoxForm(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        this.InitializeComponent();

        this.label.Text = text;
        this.Text = string.IsNullOrEmpty(caption) ? AppDomain.CurrentDomain.FriendlyName : caption;

        switch (buttons)
        {
            case MessageBoxButtons.OKCancel:
                this.button2.Visible = true;
                break;

            case MessageBoxButtons.AbortRetryIgnore:
                SetupButton(this.button1, DialogResult.Abort);
                SetupButton(this.button2, DialogResult.Retry);
                SetupButton(this.button3, DialogResult.Ignore);
                this.CancelButton = null;
                this.ControlBox = false;
                break;

            case MessageBoxButtons.YesNoCancel:
                SetupButton(this.button1, DialogResult.Yes);
                SetupButton(this.button2, DialogResult.No);
                SetupButton(this.button3, DialogResult.Cancel);
                this.CancelButton = this.button3;
                break;

            case MessageBoxButtons.YesNo:
                SetupButton(this.button1, DialogResult.Yes);
                SetupButton(this.button2, DialogResult.No);
                this.CancelButton = null;
                this.ControlBox = false;
                break;

            case MessageBoxButtons.RetryCancel:
                SetupButton(this.button1, DialogResult.Retry);
                SetupButton(this.button2, DialogResult.Cancel);
                break;
        }

        switch (icon)
        {
            case MessageBoxIcon.None:                    
                this.label.Width += this.label.Left - 12;
                this.label.Left = 12;

                this.Icon = null;
                this.pictureBox.Visible = false;
                break;
            
            case MessageBoxIcon.Error:
                this.SetIcon(SystemIcons.Error);
                break;
            
            case MessageBoxIcon.Question:
                this.SetIcon(SystemIcons.Question);
                break;
            
            case MessageBoxIcon.Warning:
                this.SetIcon(SystemIcons.Warning);
                break;
            
            case MessageBoxIcon.Information:
                this.SetIcon(SystemIcons.Information);
                break;
        }

        
        using (var g = this.CreateGraphics())
        {
            var size = g.MeasureString(text, this.label.Font);
            if (size.Width <= this.label.Width)
            {
                var extraWidth = this.Width - this.label.Width;
                this.Width = (int)(size.Width + extraWidth);
            }
            else
            {
                var lineHeight = (int)Math.Ceiling(size.Height);
                size = g.MeasureString(text, this.label.Font, (int)this.label.Width);

                var heightDiff = (int)size.Height - this.label.Height;
                if (heightDiff > 0)
                {
                    var extraHeight = this.Height - this.label.Height;
                    this.Height = extraHeight + (int)(Math.Ceiling(size.Height / lineHeight) * lineHeight);
                }

                this.label.TextAlign = ContentAlignment.MiddleLeft;
            }
        }
    }

    private void SetIcon(Icon icon)
    {
        if (Application.OpenForms.Count > 0)
        {
            this.Icon = Application.OpenForms[0].Icon;
        }

        this.pictureBox.Image = icon.ToBitmap();
    }

    private static void SetupButton(Button button, DialogResult result)
    {
        button.Text = TranslateButtonText != null ? TranslateButtonText(result) : $"&{result}";
        button.Visible = true;
        button.DialogResult = result;
    }

    public static DialogResult Show(string text)
    {
        return Show(text, AppDomain.CurrentDomain.FriendlyName);
    }

    public static DialogResult Show(string text, string caption)
    {
        return Show(text, caption, MessageBoxButtons.OK);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
    {
        return Show(text, caption, buttons, MessageBoxIcon.None);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        using (var form = new MessageBoxForm(text, caption, buttons, icon))
        {
            return form.ShowDialog();
        }
    }
}

TranslateButtonText allow you set text for buttons in other languages to localize your application. By default, english is used.

The last part of the contructor is used to determine the size of the dialog based in text length to show. The label has Anchor property set so here we change the form size (the label adapt to that size).

Basically you must replace Label with RichTextBox. You can expose RichTextBox as a property of the form to allow has full control (to set different colors, for example) outside of the form.

You can use like a MessageBox:

MessageBoxForm.Show("Message to show", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
MessageBoxForm.Show("All done");

Or get a form instance before show to make other things:

using (var form = new MessageBoxForm("Message to show", null, MessageBoxButtons.YesNo, MessageBoxIcon.Error))
{
    // If you replace and expose the Label, you can do this:
    //RichTextBox richTextBox = form.Message;
    //richTextBox...

    form.ShowDialog();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM