【问题标题】:Digital Clock in visual C# windows form not updating automaticallyVisual C# Windows 窗体中的数字时钟不会自动更新
【发布时间】:2015-11-17 13:03:04
【问题描述】:

我是 Visual C# windows 窗体的新手。我正在制作数字时钟,这样当我按下一个按钮时,时间就会开始并不断更新,即意味着秒数应该继续运行,当我按下停止按钮时,它应该停止。但是在我当前的代码中,时间正在显示,但它的秒数没有更新。谁能帮我。谢谢。

代码

namespace DTDemo
{
 public partial class Form1 : Form
{
    private DateTime datetime;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) // start button
    {
        datetime = DateTime.Now;
        String time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
        label1.Text = time; 
    }

    private void button2_Click(object sender, EventArgs e) //stop button
    {
        label1.Text = " ";
    }
}
}

我尝试将其放入 while(true) 中,但随后它冻结了,没有任何反应。请帮忙谢谢!

【问题讨论】:

  • 添加一个 timer 和它的 Tick 事件更新标签
  • 您需要为此使用Timer。提示:它有Start()Stop() 方法和Tick 事件。
  • 使用System.Windows.Forms命名空间中的Timer类。
  • 您的时钟只会显示您现在单击按钮时的时间。在您的程序中放置一个计时器,将其设置为每秒触发一次,并让计时器事件更新您的时钟。
  • 计时器...看起来很有趣。让我了解更多有关它的信息。顺便说一句,你能举个例子吗?

标签: c# windows forms clock


【解决方案1】:

当然不是,您需要一个计时器来不断更新标签。 请尝试以下操作:

namespace DTDemo
{
   public partial class Form1 : Form
   {
      private DateTime datetime;
      System.Timers.Timer timer = new System.Timers.Timer(1000);

      public Form1()
      {
          InitializeComponent();
          timer.Elapsed += timer_Elapsed;
      }

      void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
      {
        MethodInvoker method = new MethodInvoker(delegate{
        datetime = DateTime.Now;
        String time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
        label1.Text = time; 
        });
        if (label1.InvokeRequired)
            label1.Invoke(method);
        else
            method();
    }

      private void button1_Click(object sender, EventArgs e) // start button
      {
          timer.Start();
      }

      private void button2_Click(object sender, EventArgs e) //stop button
      {
          timer.Stop();
          label1.Text = " ";
      }
    }
  }

顺便说一句,我使用的是“System.Timers.Timer”而不是“System.Windows.Forms.Timer”,因为如果 UI 冻结,WinForms 计时器将冻结(因为它在主 UI 线程上运行)。另一方面,System.Timers.Timer 在工作线程上运行,仅将 UI 请求发布到主上下文

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2022-12-11
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多