繁体   English   中英

如何知道按键按下了多少毫秒?

[英]How to know how many miliseconds a KEY pressed?

我只是使用热键在游戏中创建移动。我想为X时间添加保持键。我想知道有没有办法知道一个键按下了多少毫秒?

首先,创建几个 class 成员来保存按下的键和时间。

private KeyChar _pressedKey;
private Stopwatch _keyPressStopwatch = new Stopwatch();

然后编写您的KeyDown事件处理程序以将值放入这些变量中:

private void KeyPressed(object sender, KeyEventArgs e)
{
    _keyPressStopwatch.Restart();
    _pressedKey = e.KeyChar;
}

现在编写一个KeyUp事件处理程序来完成 rest 的工作:

private void KeyReleased(object sender, KeyEventArgs e)
{
    if (e.KeyChar != _pressedKey)  // We only care about the last key pressed.
        return;

    _keyPressStopwatch.Stop();
    double milliseconds = _keyPressStopwatch.ElapsedMilliseconds;

    // milliseconds is now how long the key was pressed. Do something with it.
}

不要忘记订阅与此关联的任何控件的KeyDownKeyUp事件。

编辑

评论中提出了关于计时精度的一个很好的观点,因此我将代码从使用DateTime.UtcNow切换到使用Stopwatch

public partial class Test : Form
{
   private int _iteration = 0;
    private Stopwatch _sw;
    private int _pressedKey;

    public Test()
    {
        InitializeComponent();
    }

    private void Test_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyValue == _pressedKey) return;
        _iteration++;
        _sw = new Stopwatch();
        _sw.Start();
        _pressedKey = e.KeyValue;
    }

    private void Test_KeyUp(object sender, KeyEventArgs e)
    {
        _pressedKey = -1;
        label1.Text = $"Iteration:{_iteration}. Elapsed: {_sw.ElapsedMilliseconds}ms";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM