如何在c# windows应用程序中根据用户输入设置定时器控制

本文关键字:用户 输入 设置 控制 定时器 windows 应用程序 | 更新日期: 2023-09-27 18:07:23

我需要关于定时器控制的帮助,我想设置用户输入后的时间,即表单运行后的用户输入在文本框中10:30 AM,然后标签上的计时器将从10:30 AM开始继续…

如何在c# windows应用程序中根据用户输入设置定时器控制

使用此代码希望对您有所帮助..... WindowsFormsApplication1

名称空间{公共部分类Form1: Form{静态Int32秒= 0;静态Int32分钟= 0;字符串m;字符串年代;公共Form1 (){InitializeComponent ();}

    private void button1_Click(object sender, EventArgs e)
    {
         m = textBox1.Text.Substring(0, 2);
        s = textBox1.Text.Substring(3, 2);
        sec = Convert.ToInt32(s);
        minut = Convert.ToInt32(m);
        timer1.Start();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        sec++;
        if(sec>59)
        {
            sec = 1;
            minut++;
        }
        if(minut>59)
        {
            minut = 0;
        }
        label1.Text = minut.ToString() + ":" + sec.ToString();
        //second = second + 1;
        //if (second >= 10)
        //{
        //    timer1.Stop();
        //    MessageBox.Show("Exiting from Timer....");
        //}
    }

}

}

这是一个使用基本BackGroundWorker将时钟从WinForms应用程序中输入的日期/时间提前60秒的示例。如果您更愿意使用实际时间,请更改DateTime begin = DateTime. parse (textbox_1.Text);to DateTime begin = DateTime. now;——这不是世界上最迷人的解决方案,但它可以完成工作,并且值得思考。好运!

System.ComponentModel.BackGroundWorker textTime = new System.ComponentModel.BackGroundWorker();// use a reference Using System.ComponentModel; to avoid all this typing
private void button1_Click(object sender, EventArgs e){//this event could be a button click, or whatever else you want to start the process
    textTime.DoWork+= beginTextTimer;
    textTime.RunWorkerAsync();
}
private void beginTextTimer(object sender, DoWorkEventArgs e){
     DateTime begin = DateTime.Parse(textbox_1.Text);//assumes you've already done validation - use DateTime.Now if you don't require user's input
     int totalSeconds = 0;
     While(totalSeconds < 60){
        totalSeconds = DateTime.Now.Subtract(begin).TotalSeconds;//since you're pausing 1 second, you could just increment an integer here rather than doing a DateTime calculation - this works no matter what the pause is
         MethodInvoker mI = () => { 
             textBox_1.Text = begin.AddSeconds(totalSeconds).ToString(); 
         };
         BeginInvoke(mI);//these two lines invoke back to the UI thread to change the textbox value    
         System.Threading.Thread.Sleep(1000);     
      }
}