您可以跟踪当前按住的键。像这样的东西
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();
}
}