使用效果:
代码:
#region 消息框变量
private Timer fadeTimer; // 定义计时器
private int fadeSpeed = 2;//淡出速度
private NotifyIcon notifyIcon;//气泡通知
private int opacityLevel = 10;//不透明度
public enum NotificationType
{
Error,//错误
Warning,//警告
Info//提示
}
#endregion
#region 消息提醒
public void NMessage(string message, NotificationType Type)
{
fadeTimer = new Timer();
fadeTimer.Tick += FadeTimer_Tick;
notifyIcon = new NotifyIcon();
notifyIcon.Visible = true;
// 根据类型选择合适的图标和错误类型
switch (Type)
{
case NotificationType.Error:
notifyIcon.Icon = SystemIcons.Error;
notifyIcon.ShowBalloonTip(2000, "错误", message, ToolTipIcon.Error);
break;
case NotificationType.Warning:
notifyIcon.Icon = SystemIcons.Warning;
notifyIcon.ShowBalloonTip(2000, "警告", message, ToolTipIcon.Warning);
break;
default:
notifyIcon.Icon = SystemIcons.Information;
notifyIcon.ShowBalloonTip(2000, "提示", message, ToolTipIcon.Info);
break;
}
// 显示气球提示框
// 开始计时器,渐渐地隐藏消息框
fadeTimer.Start();
}
private void FadeTimer_Tick(object sender, EventArgs e)
{
// 逐渐减小消息框的不透明度
opacityLevel -= fadeSpeed;
notifyIcon.Visible = opacityLevel > 0;
if (opacityLevel <= 0)
{
// 当不透明度减小到0时停止计时器
fadeTimer.Stop();
// 关闭 NotifyIcon
if (notifyIcon != null)
{
notifyIcon.Dispose();
notifyIcon.Visible = false;
}
}
}
#endregion
使用消息框:
NMessage($"修改失败{ex.Message}", NotificationType.Error);//错误提示
NMessage($"删除{Name}成功", NotificationType.Info);//普通提示
NMessage($"删除{Name}成功", NotificationType.Warning);//警告提示