【问题标题】:C# GUI creating a running clock while doing another task in the same formC# GUI 在以相同形式执行另一个任务时创建运行时钟
【发布时间】:2014-03-03 16:00:21
【问题描述】:

如何在表单打开时运行时钟?

我正在使用此代码:

DateTime present = DateTime.Now;

label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString();

我想要一个在打开表单时运行的时钟,并且应该能够在时钟运行时单击其他对象。

【问题讨论】:

  • 到目前为止您尝试过什么,您在尝试中遇到了什么问题?详细解释问题。
  • 对不起,我刚开始学习,不太了解c#中的函数

标签: c# multithreading user-interface clock


【解决方案1】:

您需要创建 System.Threading.Timer 对象并在它的 Tick 事件上更新您的标签文本。这样做也更正确

    DateTime.Now.ToString("hhMMss");

或

    DateTime.Now.ToShortTimeString();

而不是几个 .ToString() 调用。

结果代码会是这样的

    new System.Threading.Timer((state) => { BeginInvoke((Action)delegate() { label1.Text = DateTime.Now.ToShortTimeString(); }); }, null, 1000, 1000);

【讨论】:

  • 检查我的第二种方法。也许它符合您正在尝试的要求。
  • @blacai 您的解决方案在 WPF 项目中都是可以接受的。我在 WinForms 中。
  • 是的,你是对的,但他应该将选择的一个标记为解决方案。
【解决方案2】:

你可以试试DispatcherTimer类

    DispatcherTimer dpTimer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();
        dpTimer.Tick += new EventHandler(dpTick);
        dpTimer.Interval = new TimeSpan(0, 0, 1);
        dpTimer.Start();
    }

    private void dpTick(object sender, EventArgs e)
    {
        DateTime present = DateTime.Now;
        timer_label.Content = present.Hour.ToString() + present.Minute.ToString() + present.Second.ToString();
    }

如果您想使用计时器,请查看此解决方案:

        new System.Threading.Timer((state) => 
        {
            Action action = () => timer_label.Content = DateTime.Now.ToString("hh:MM:ss");
            Dispatcher.BeginInvoke(action);
        }, null, 1000, 1000);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多