Winform窗体程序 自定义弹框自动关闭

1.指定要弹出的消息以及定时的时间(单位秒)

2.弹出后,对话框上的确定按钮上会动态倒计时,当时间为0时自动关闭,也可以通过点击确定按钮关闭

TimingMessageBox是一个窗体

核心代码

public partial class TimingMessageBox : Form

    {

        // 自动关闭的时间限制,如3为3秒后自动关闭

        private int second;

        // 计数器,用以判断当前窗口弹出后持续的时间

        private int counter;



        // 构造函数

        public TimingMessageBox(string message, int second)

        {

            InitializeComponent();

            // 显示消息

            this.labelMessage.Text = message;

            // 获得时间限制

            this.second = second;

            // 初始化计数器

            this.counter = 0;

            // 初始化按钮的文本

            this.buttonOK.Text = string.Format("确定({0})", this.second - this.counter);

            // 激活并启动timer,设置timer的触发间隔为1000毫秒(1秒)

            this.timer1.Enabled = true;

            this.timer1.Interval = 1000;

            this.timer1.Start();

        }



        private void timer1_Tick(object sender, EventArgs e)

        {

            // 如果没有到达指定的时间限制

            if (this.counter <= this.second)

            {

                // 刷新按钮的文本

                this.buttonOK.Text = string.Format("确定({0})", this.second - this.counter);

                this.Refresh();

                // 计数器自增

                this.counter++;

            }

            // 如果到达时间限制

            else

            {

                // 关闭timer

                this.timer1.Enabled = false;

                this.timer1.Stop();

                // 关闭对话框

                this.Close();

            }

        }



        private void buttonOK_Click(object sender, EventArgs e)

        {

            // 单击确定按钮,关闭对话框

            this.Close();

        }

    }

然后在主窗体中调用:

 

public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }



        private void buttonShowMessageBox_Click(object sender, EventArgs e)

        {

            string message = this.textBoxMessage.Text.Trim();

            int second = Convert.ToInt32(this.textBoxSecond.Text.Trim());

            TimingMessageBox messageBox=new TimingMessageBox(message,second);

            messageBox.ShowDialog();

        }

    }

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值