在软件开发中,很多地方需要用到与用户消息提醒,用form绘制一个自己消息框。
首先在界面上绘制两个按钮,在之前文章有教程绘制一个button方法,也可以直接使用系统。
私有属性
#region 私有属性
private string message;
private MesBoxIcon mesIcon;
#endregion
公有属性
#region 公有属性
public MesBoxIcon MesIcon
{
get => mesIcon;
set
{
mesIcon = value;
this.Invalidate();
if (value == MesBoxIcon.Info)
{
wenImageButton1.Visible = false;
}
}
}
public string Message
{
get => message;
set
{
message = value;
Graphics g = this.CreateGraphics();
SizeF sizef = g.MeasureString(value, this.Font);
int width =(int) sizef.Width + this.FrameWidth * 2 + 80;
int height = this.TitleHeight + this.FrameWidth + panel1.Height;
this.Size = new Size(this.Width < width ? width : this.Width, this.Height < height ? height : this.Height);
this.Invalidate();
}
}
#endregion
MesBoxIcon 消息类型选择
找到与自己需要绘制的图档
public enum MesBoxIcon { Asterisk, Error, Info, Warning, }
采用GDI绘制消息框
protected override void OnPaint(PaintEventArgs e)
{ base.OnPaint(e);
Rectangle rec = new Rectangle(this.FrameWidth, this.TitleHeight, this.Width - this.FrameWidth * 2, this.Height - this.TitleHeight - this.FrameWidth - panel1.Height);
Rectangle recStr = new Rectangle(rec.X + 70, rec.Y, rec.Width - 70, rec.Height); Rectangle recIco = new Rectangle(rec.X + 5, rec.Y + (rec.Height - 60) / 2, 60, 60);
Graphics g = e.Graphics; g.DrawString(Message, Font, new SolidBrush(this.ForeColor), recStr, WenSkin.Controls.ControlHelper.StringConters);
switch (MesIcon)
{
case MesBoxIcon.Asterisk:
g.DrawImage(Properties.Resources.Asterisk, recIco);
break;
case MesBoxIcon.Error:
g.DrawImage(Properties.Resources.error, recIco);
break;
case MesBoxIcon.Info:
g.DrawImage(Properties.Resources.Info, recIco);
break;
case MesBoxIcon.Warning:
g.DrawImage(Properties.Resources.Warning, recIco);
break;
default:
break;
}
}
两个按钮点击事件
private void wenImageButton2_Click(object sender, EventArgs e)
{ this.DialogResult = DialogResult.OK; }
private void wenImageButton1_Click(object sender, EventArgs e)
{ this.DialogResult = DialogResult.Cancel; }
可以根据自己需求更改。
多个构造函数示例
public MesBox()
{
InitializeComponent();
this.SizeChanged += (s, e) =>
{
if (wenImageButton1 != null)
wenImageButton1.Width = (this.Width - this.FrameWidth * 2) / 2;
};
Text = "消息";
mesIcon = MesBoxIcon.Info;
this.StartPosition = FormStartPosition.CenterScreen;
}
public MesBox(string text) : this()
{
Message = text;
}
public MesBox(string text,MesBoxIcon mesBoxIcon) : this(text)
{
MesIcon = mesBoxIcon;
switch (MesIcon)
{
case MesBoxIcon.Asterisk:
Text = "提醒";
break;
case MesBoxIcon.Error:
Text = "错误";
break;
case MesBoxIcon.Info:
Text = "消息";
break;
case MesBoxIcon.Warning:
Text = "警告";
break;
default:
break;
}
}
public MesBox(string text,string caption, MesBoxIcon mesBoxIcon) : this(text)
{
Text = caption;
}
至此,一个自主弹窗绘制完成
接下来调用
var m = new MesBox(text, MesBox.MesBoxIcon.Asterisk).ShowDialog();
if (m == DialogResult.OK)
true;
else
false;
一行代码即可,是不是很方便。
关注文林软控,带你一起C# 美化.NET 控件。