0

This is my second question on StackOverflow here. I posted my first question a while ago and got a working reply in no time, much impressed, much appreciated.

Anyways, so what I want to know is, how to get a DispatcherTimer to work and show time in a certain textbox and stop it when it reaches a certain time (let's say 60 seconds) and perform a function after 60 seconds.

What I'm basically using this for is :

Making a game, which has to stop after 60 seconds and show the scores or related stuff. So this requires me to show the time in a textbox and perform a function at 60 seconds or after that.

Here's more information :

Textbox is called "timerbox"

Here's the code I've tried :

    DispatcherTimer dt = new DispatcherTimer();

    private void TimerStart(object sender, RoutedEventArgs e)
    {
        dt.Interval = TimeSpan.FromSeconds(1);
        dt.Tick += dt_Tick;
        dt.Start();
    }

    int count = 0;
    void dt_Tick(object sender, object e)
    {
        count = count + 1;
        timerbox.Text = Convert.ToString(count);
    }

It doesn't show the time in textbox, plus I don't know how to make it stop at certain point and perform a function.

Thank you for reaching here, please leave answers with full explanation as I'm a complete beginner :)

P.S. I'm using Windows Store App Development Environment in Visual Studio 2013. And there's no "Timer" in it as there is in normal C# Environment.

4

2 回答 2

0

AOA。我最近开始学习c#。(对 Windows 窗体应用程序感兴趣)。希望这对您有所帮助。

如果您只想为窗帘活动设置计时器.....

建议您使用计时器(在工具箱中)......

按照步骤,当您双击 timer1 VS 将为您创建一个 timer1_Tick 函数,该函数将在您计时器滴答的每个计时器中被调用.....现在当 timer1 icks 写在那里时您想要做什么......就像这样……

private void timer1_Tick(object sender, EventArgs e)
    {
        //enter your code here
    }

现在写timer1。和 VS 将显示可用功能的列表.... 例如,

timer1.Interval = (60*1000); //enter time in milliseconds

现在当你想开始写......

timer1.Start();

并在任何计时器调用时停止计时器

timer1.Stop();

如果您想重复计时器,只需在该刻度函数中写入 timer1.start() .....

另外,设置文本框文本等于 timer1 时间使用类似

textBox1.Text = Convert.ToString(timer1.Interval);

单击此处了解有关计时器类的更多信息

希望对您有所帮助,如有任何困惑,请发表评论......

于 2014-07-27T16:27:06.227 回答
0

DispatcherTimer 的正常流程如下所示:

  1. 首先设置您的新对象,设置一个新的 EventHandler,它将在每个 Tick 运行您所需的代码,并为所需的 Tick Interval 设置时间跨度。

    public MainPage()
    {
        this.InitializeComponent();            
    
        timer = new DispatcherTimer();
        timer.Tick += new EventHandler<object>(timer_Tick);
        timer.Interval = TimeSpan.FromMilliseconds(bpm);
    }
    
  2. 设置 Timer_Tick 事件

    async Void timer_Tick(object Sender, object e)
    {
    await this.Dispatcher.RunAsync(Windows.UI.core.CoreDispatcherPriority.High, () => 
    {
    //Run the Code
    textBox1.text = timer.interval.TotalMilliseconds.ToString();
    });
    
  3. 您必须有一个触发器来启动 Dispatcher(并在需要时停止),例如一个按钮

    private void StartButton_Click() 
    {
    timer.Start();
    }
    
  4. 此示例是使用 VS2015 中的新 windows 10 通用应用程序平台完成的,但我认为它在普通 windows 8 应用程序中应该看起来差不多

于 2015-11-20T14:25:23.773 回答