c# - 在 WinForm 上运行数字时钟

标签 c# winforms timer

您好,我必须设计一个具有简单文本框的 Windows 窗体。文本框包含一个类似文本的计时器(00:00 格式)。

我想每秒刷新一次页面,让文本框的内容随之变化。 (就像一个数字时钟,运行一小时!)。

我发现我需要使用 System.Windows.Forms.Timer 类,并且我已将 Timer 项从工具箱放到我的表单中。

接下来...我需要使用 Thread.Sleep(1000) 函数吗...有什么想法吗?

这是我一直在尝试的代码片段。我知道程序哪里出错了,thread.sleep() 部分甚至让我的代码运行起来更糟。我尝试了 ToolBox 中的 Timer 东西,但无法通过。(当我运行代码时,它编译成功,然后由于肮脏的 For 循环,应用程序卡住了一小时)帮助!!

  public  partial class Form1 : Form
{
    Button b = new Button();
    TextBox tb = new TextBox();
    //System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();

    public Form1()
    {
        b.Click += new EventHandler(b_click);
        b.Text = "START";
        tb.Text = "00 : 00";
        //timer1.Enabled = true;
        //timer1.Interval = 1000;
        tb.Location = new Point(100, 100);
        this.Controls.Add(tb);
        this.Controls.Add(b);
        InitializeComponent();
    }

    private void refreshTimer_Tick()
    {

       for (int i = 0; i < 60; i++)
        {
            for (int j = 0; j < 60; j++)
            {
                Thread.Sleep(500);
                string TempTime = string.Format("{0:00} : {1:00}",i,j);
                tb.Text = TempTime;                    
                Thread.Sleep(500);

            }
        }
    }
    public void b_click(object sender, EventArgs e)
    {
        refreshTimer_Tick();

    }
}

最佳答案

设置定时器和刷新周期。 (1 秒)

timer1.Enabled = true;
timer1.Interval = 1000;

然后您需要实现您希望计时器每 1 秒执行的操作:

private void timer1_Tick(object sender, EventArgs e)
{
    DigiClockTextBox.Text = DateTime.Now.TimeOfDay.ToString();
}

关于c# - 在 WinForm 上运行数字时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8678162/

相关文章:

java - 在 Unity Project 之间共享数据到 Android Studio java 代码

c# - NUnit 自定义属性同时表现为 TestAttribute 和 CategoryAttribute

c# - 调用线程无法访问此对象,因为另一个线程拥有它

c# - 将 html 表格拖放到另一个应用程序中

C# ReportViewer 带参数的本地报表

android - 如何在android中高效地使用定时器?

c# - 当我单击asp.net中gridview上的标题文本时如何对gridview进行排序

c# - 在 C# Winform 应用程序中设置 DataGridView 行背景图像

javascript - 让这个计时器从一个按钮开始

c - 如何在 C 中以毫秒为单位获取程序的执行时间?