Keydown推迟了

时间:2013-07-06 23:10:37

标签: c# onkeydown

我有这个以避免无限的keydown循环:

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (bKeyIsDown) bKeyIsDown = false;
        bKeyIsDown = true;
        base.OnKeyDown(e);
    }
    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);
        bKeyIsDown = false;
    }

问题在于,如果我同时按下2个键,它只会按下第一个键的动作。此外,如果您按下某个键并按下该键,则按下另一个键将会延迟该键的操作。

有没有办法解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:3)

您可以跟踪当前按下的按键。像这样的东西

bool bKeyIsDown = false;
Keys currentKey = Keys.None;

public event EventHandler OnKeyPressedOnce;

protected override void OnKeyDown(KeyEventArgs e)
{
    if (bKeyIsDown && currentKey == e.KeyCode)
        e.SuppressKeyPress = true;
    else
    {
        currentKey = e.KeyCode;       

        //have your class handle this event and play the sound when this fires    
        //Could also create custom EventArgs and pass the key pressed 
        if(OnKeyPressedOnce != null)
           OnKeyPressedOnce(null, EventArgs.Empty);

        bKeyIsDown = true;
    }

    base.OnKeyDown(e);
}


protected override void OnKeyUp(KeyEventArgs e)
{
    bKeyIsDown = false;
    base.OnKeyUp(e);
}

如果您希望一次处理两个以上的键,则可以存储按下的键列表,而不仅仅是当前键。

评论更新。这是处理事件的基本要点。

private void KeyPressedOnce_PlaySound(object sender, EventArgs e)
{
    if (currentKey == Keys.A)
    { 
        MediaPlayer p1 = new MediaPlayer();
        p1.Open(new System.Uri(wav1Path));
        p1.Play();
    }


    if (currentKey == Keys.S)
    {
        MediaPlayer p2 = new MediaPlayer();
        p2.Open(new System.Uri(wav2Path));
        p2.Play();
    }
}