2013-07-06 56 views
2

我有這樣避免無限的keydown循環: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個鍵,只將做第一個壓制的作用。此外,如果您按下某個按鍵並按下該按鍵,則會按下另一個按鍵,該按鍵的動作將會延遲。

有沒有辦法解決這個問題?謝謝!

+0

你想做什麼? – keyboardP

+0

在按鍵關閉時播放聲音,並在釋放按鍵時停止播放。 – Joscplan

回答

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(); 
    } 
} 
+0

鑰匙關閉時仍然打圈。 – Joscplan

+0

您需要在'else {}'塊中播放聲音。您可以通過處理其OnKeyDown/Up事件在常規文本框上執行此操作,或者如果您多次使用文本框,則可以在該程序段中處理該塊中的自定義事件。 – keyboardP

+0

我已更新代碼以顯示事件處理程序的示例 – keyboardP