2012-12-17 42 views
0

我想在winfor應用程序中移動一些圖形。要做到這一點,我需要知道是否有任何光標鍵被按下。我試圖覆蓋ProcessCmdKey,但沒有成功。捕獲光標鍵的KeyDown和KeyUp事件

任何提示/想法如何實現?

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{ 
    switch (keyData) 
    { 
     case Keys.Left: 
      // while Left is down 
      // call this method repeadetdly 
      buttonGoLeft(); 
      // when key is up stop calling this method 
      // and check for other keys 
      return true; 

     //Other cases 
    } 
    } 
+0

表單沒有捕獲事件嗎? –

+0

它捕捉事件,但我有問題放置一個while循環,所以當任何光標鍵被按下時,我需要的方法被重複調用。 –

+0

重複調用「ProcessCmdKey」方法嗎? –

回答

1

This works!

using System.Windows.Forms; 

namespace WindowsFormsApplication5 
{ 
    public partial class Form2 : Form 
    { 
     public Form2() 
     { 
      InitializeComponent(); 
      KeyPreview = true; 
     } 

     protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
     { 
      switch (keyData) 
      { 
       case Keys.Left: 
        // while Left is down 
        // call this method repeadetdly 
        MessageBox.Show("its left", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
        // when key is up stop calling this method 
        // and check for other keys 
        return true; 

       default: 
        return false; 
      } 
     } 
    } 
} 
+0

任何投下的理由? –