自建MessageBox

本文介绍如何因为系统MessageBox不支持颜色修改,而自建一个具备颜色定制功能的MessageBox。通过创建新的窗体类`MessageBoxForm`,并实现不同样式和颜色设置,以及提供一个扩展类`MessageBoxExt`方便替换原有MessageBox调用,以达到自定义效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于需要修改MessageBoxbox的颜色,而系统自带的MessageBox并不支持颜色修改,故而新建一个MessageBox。

创建一个新窗体,然后在命名空间中直接添加程序

namespace ProcessVisualization

{

//枚举MessageBox类型

  public enum MessageBoxStyle

{

OK=0;

OKCancel=1;

}


public partial class MessageBoxForm:Form

{

public MessageBoxForm(MessageBoxStyle messageBoxStyle, string msg)

{

InitializeComponent();

//添加警告图片

Icon image=ProcessVisualization.Properties.Resources.warn;

pictureBox1.Image=image.ToBitmap();

if (messageBoxStyle==MessageBoxStyle.OK_

{

button1.Visible=true;//确定键

button2.Visible=false;//取消键

button1.Text="确定";

}

else

{

button1.Visible=true;

button2.Visible=true;

button1.Text="确定";

button2.Text="取消";

}

//文字内容

this.label1.Text=msg;

//设置颜色

this.BackColor=Color.FromArgb(51,51,51);

this.ForeColor=Color.White;

button1.BackColor=Color.FromArgb(179,179,179);

button1.ForeColor=Color.Black;

button2.BackColor=Color.FromArgb(179,179,179);

button2.ForeColor=Color.Black;

//设置位置

SizeF size=TextRenderer.MeasureText(msg,this.Font);

this.Width=(int)size.Width+300;

this.Height=(int)size.Height+150;

int x=0;

int y=0;

if (messageBoxStyle==MessageBoxStyle.OK)

{

x=(int)size.Width+300-110;

y=(int)size.Height+150-80;

button1.Location=new Point(x,y);

}

else

{

x=(int)size.Width+300-190;

y=(int)size.Height+150-80;

button1.Location=new Point(x,y);

x=(int)size.Width+300-110;

y=(int)size.Height+150-80;

button2.Location=new Point(x,y);

}

}

}

}

然后在相应按钮中添加事件即可。

若已在整个程序中应用MessageBox,此时修改为自己写的MessageBox的程序修改量太大,则可新建一个类,命名为MessageBoxExt,然后在其中添加程序:

class MessageBoxExt

{

public static DialogResult Show(string text,string caption,MessageBoxButtons buttons,MessageBoxIcon icon)

{

if (buttons==MessageBoxButtons.OKCancel)

{

return new MessageBoxForm(MessageBoxStryle.OKCancel,text).ShowDialog();

}

else

{

return new MessageBoxForm(MessageBoxStyle.OK,text).ShowDialog();

}

}

}

然后将原程序中所有调用MessageBox的地方改为MessageBoxExt即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值