状态条和时间

Ton*_*ony 0 c#

我正在创建一个游戏...我想添加一个计数器作为一个时钟与微软solitair游戏中的时间计数器完全相同,我希望以后当游戏超过时间停止并且时间到达时保存在变量中但是我想用这个数字来生成一个分数表.

提前完成....我会在100%完成时发布整个游戏所以你们可以享受:-)

Ton*_*ion 6

您可以使用Stopwatch对象.

以下是如何使用它的链接:http: //msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

要启动秒表,请执行以下操作:

Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
Run Code Online (Sandbox Code Playgroud)

停止:

stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed; // gets elapsed time
Run Code Online (Sandbox Code Playgroud)

要显示已过去的时间:

// Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
Run Code Online (Sandbox Code Playgroud)

现在,您可以在条带中显示"elapsedtime"字符串.

编辑:

要查看移动时间,请在按钮单击处理程序中输入以下开始时间:

    // global variable
        string timeelepse = string.empty; 
   // in button click handler
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();


            sw.Start();

            System.Threading.Thread t = new System.Threading.Thread(delegate()
            {
                while (true)
                {
                TimeSpan ts = sw.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);

                timeelepse = elapsedTime;

                  UpdateLabel();
                }
            });
            t.Start();
Run Code Online (Sandbox Code Playgroud)

现在将这两个函数和委托添加到您的表单类:

public delegate void doupdate();
        public void UpdateLabel()
        {
            doupdate db = new doupdate(DoUpdateLabel);
            this.Invoke(db);
        }

        public void DoUpdateLabel()
        {
            toolStripStatusLabel1.Text = timeelepse;
        }
Run Code Online (Sandbox Code Playgroud)