亲宝软件园·资讯

展开

C# Winform通知效果

代码迷途​​​​​​​ 人气:0

前言

本文主要介绍其具体的实现思路(视频仅有代码输入,并无过程介绍等),同时,在原本实现的基础上,进行了多处修改和优化,具体参见下面的内容。

优化调整

下面是对源代码的修改、优化和调整:

下图为示例,后半段显示的内容是设置最多显示5个消息框时,发生替换的效果;

// 设置通知的数量
Form_Alert.AlertFormNum = 5;
Form_Alert.MoveEntry = false;// 不水平移动进入

水平移动进入的效果(默认):

/// <summary>
/// 设置完x、y之后执行初始化启动。设置位置、消息类型、显示、倒计时
/// </summary>
/// <param name="msg"></param>
/// <param name="msgType"></param>
/// <param name="msgFont">字体,默认不指定即可</param>
private void InitStart(string msg, MsgType msgType, Font msgFont = null)
{
    // ...
}

调用并显示自定义通知

新建项目NotificationCustom,完成通知框的调用显示

Form_Alert.ShowNotice("这是一条成功的消息", MsgType.Success);

Form_Alert.ShowNotice("警告!警告的消息", MsgType.Warning);

Form_Alert.ShowNotice("发生了错误,禁止!", MsgType.Error);

Form_Alert.ShowNotice("一条普通的信息记录", MsgType.Info);

或者显示时指定字体(下面为随机字体)

Form_Alert.ShowNotice("这是一条成功的消息", MsgType.Success, new Font(FontFamily.Families[random.Next(0, FontFamily.Families.Length)], (float)(10.0+10.0*random.NextDouble())));

主要实现过程

代码实现

修改后全部代码不到200行,如下,主要部分已经进行注释:

namespace CustomAlertBoxDemo
{
    public enum NotificationFormAction
    {
        start,
        wait,
        close
    }
    public enum MsgType
    {
        Success,
        Warning,
        Error,
        Info
    }
    public partial class Form_Alert : Form
    {
        /// <summary>
        /// 通知窗体的数量,默认为垂直屏幕几乎占满的数量
        /// </summary>
        private static int alertFormNum = Screen.PrimaryScreen.WorkingArea.Height / (75 + 5); // 75为窗体高度,如果调整窗体高度,记得修改此处
        /// <summary>
        /// 通知窗体的数量,默认为垂直屏幕几乎占满的数量,手动修改的数量不能超出屏幕和低于1,否则设置无效
        /// </summary>
        public static int AlertFormNum
        {
            get => alertFormNum;
            set
            {
                if (value <= Screen.PrimaryScreen.WorkingArea.Height / (75 + 5) && value > 0)
                {
                    alertFormNum = value;
                }
            }
        }
        /// <summary>
        /// 自定义通知的显示时间,单位为毫秒,默认为3分钟,之后开始消失。可根据需要修改
        /// </summary>
        public static int ShowTime { get; set; } = 3000;
        /// <summary>
        /// 是否移动进入,默认true
        /// </summary>
        public static bool MoveEntry { get; set; } = true;
        /// <summary>
        /// 创建通知窗体
        /// </summary>
        /// <param name="name">窗体名称,必须指定</param>
        public Form_Alert(string name)
        {
            InitializeComponent();
            Name = name;
            this.Opacity = 0.0;
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.Manual;
        }
        private NotificationFormAction action = NotificationFormAction.start;
        /// <summary>
        /// 当前消息框的标准位置
        /// </summary>
        private int x, y;
        private void timer1_Tick(object sender, EventArgs e)
        {
            switch (this.action)
            {
                case NotificationFormAction.wait:
                    timer1.Interval = ShowTime;
                    action = NotificationFormAction.close;
                    break;
                case NotificationFormAction.start:
                    this.timer1.Interval = 100;
                    this.Opacity += 0.1;
                    if (this.x < this.Location.X)
                    {
                        this.Left-=20; // 移动快点
                    }
                    else
                    {
                        if (this.Opacity == 1.0)
                        {
                            action = NotificationFormAction.wait;
                        }
                    }
                    break;
                case NotificationFormAction.close:
                    timer1.Interval = 100;
                    this.Opacity -= 0.1;
                    this.Left -= 20;
                    if (base.Opacity == 0.0)
                    {
                        timer1.Stop();
                        base.Close();
                    }
                    break;
            }
            // tag记录下次执行的时间,用于后续的替换
            timer1.Tag = DateTime.Now.AddMilliseconds(timer1.Interval);
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            timer1.Interval = 100;
            action = NotificationFormAction.close;
        }
        /// <summary>
        /// 设置完x、y之后执行初始化启动。设置位置、消息类型、显示、倒计时
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="msgType"></param>
        private void InitStart(string msg, MsgType msgType)
        {
            //this.Location = new Point(frm.x, frm.y);
            this.Location = new Point(x + (MoveEntry?Width / 2:0), y);
            switch (msgType)
            {
                case MsgType.Success:
                    pictureBox1.Image = Resources.success;
                    BackColor = Color.SeaGreen;
                    break;
                case MsgType.Error:
                    pictureBox1.Image = Resources.error;
                    BackColor = Color.DarkRed;
                    break;
                case MsgType.Info:
                    pictureBox1.Image = Resources.info;
                    BackColor = Color.RoyalBlue;
                    break;
                case MsgType.Warning:
                    pictureBox1.Image = Resources.warning;
                    BackColor = Color.DarkOrange;
                    break;
            }
            lblMsg.Text = msg;
            Show();
            timer1.Start();
        }
        public static void ShowNotice(string msg, MsgType msgType)
        {
            Form_Alert willDisappearFrm = null;
            for (int i = 1; i < alertFormNum+1; i++)
            {
                string fname = "alert" + i.ToString();
                Form_Alert frm = (Form_Alert)Application.OpenForms[fname];
                if (frm == null)
                {
                    frm = new Form_Alert(fname);
                    frm.x = Screen.PrimaryScreen.WorkingArea.Width - frm.Width - 5;
                    frm.y = Screen.PrimaryScreen.WorkingArea.Height - frm.Height * i - 5 * i;
                    // 设置完x、y之后执行初始化启动
                    frm.InitStart(msg, msgType);
                    return;
                }
                else
                {
                    if (willDisappearFrm == null)
                    {
                        willDisappearFrm = frm;
                    }
                    else
                    {
                        if (willDisappearFrm.action < frm.action)
                        {
                            willDisappearFrm = frm;
                        }
                        else if (willDisappearFrm.action == frm.action)
                        {
                            // 不考虑一次没执行的情况
                            if (willDisappearFrm.timer1.Tag!=null&& frm.timer1.Tag != null)
                            {
                                if (willDisappearFrm.timer1.Tag == null)
                                {
                                    willDisappearFrm = frm;
                                }
                                else if(frm.timer1.Tag != null)
                                {
                                    if ((DateTime)willDisappearFrm.timer1.Tag > (DateTime)frm.timer1.Tag)
                                    {
                                        willDisappearFrm = frm;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 当前最早要消失的窗体willDisappearFrm被替换
            var newfrm = new Form_Alert(willDisappearFrm.Name);
            newfrm.x = Screen.PrimaryScreen.WorkingArea.Width - newfrm.Width - 5;
            newfrm.y = willDisappearFrm.Location.Y;
            // 必须立即替换name
            var totalNum = 0;
            foreach (Form form in Application.OpenForms)
            {
                if (form is Form_Alert)
                {
                    totalNum += 1;
                }
            }
            willDisappearFrm.Name = $"Form_Alert{totalNum + 1}";
            willDisappearFrm.pictureBox2_Click(null, null);
            // 设置完x、y之后执行初始化启动
            newfrm.InitStart(msg, msgType);
        }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论