为什么System.Timers.Timer timer1没有启动?

时间:2017-05-07 00:28:15

标签: c#

我正在尝试执行一个程序,如果按住向上箭头键,该程序应该增加label1中的数字。释放后,label1应保持其当前值。类似地,向下箭头键应该减少标签中显示的值。到目前为止,我有以下代码(我只是显示主类,方法和字段),我无法弄清楚为什么程序什么也不做。

public partial class Form1 : Form
{
    private bool _downArrowPressed;
    private bool _upArrowPressed;
    private int num = default(int);

    System.Timers.Timer timer1 = new System.Timers.Timer { Interval = 100 };

    public Form1()
    {
        InitializeComponent();
        timer1.Elapsed += new System.Timers.ElapsedEventHandler (ChangeText);
    }

    private void ChangeText(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (_downArrowPressed)
            label1.Text = num--.ToString();
        else if (_upArrowPressed)
            label1.Text = num++.ToString();
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Down:
                _downArrowPressed = true;
                timer1.Start();
                break;
            case Keys.Up:
                _upArrowPressed = true;
                timer1.Start();
                break;
        }
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Down:
                _downArrowPressed = false;
                timer1.Stop();
                break;
            case Keys.Up:
                _upArrowPressed = false;
                timer1.Stop();
                break;
        }
    }
}  

1 个答案:

答案 0 :(得分:0)

您需要通过从工具箱enter image description here

拖动此组件来使用System.Windows.Forms.Timer

将其替换为System.Timers.Timer