2

我有这个以避免无限的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 个键,它只会执行第一个按下的操作。此外,如果您正在按下一个键并且在按下它时按下另一个键,则该键的动作将被延迟。

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

4

1 回答 1

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();
    }
}
于 2013-07-06T23:29:39.310 回答