捕获光标键的KeyDown和KeyUp事件

时间:2012-12-17 13:55:24

标签: c# winforms key keydown keyup

我想在winfor应用程序中移动一些图形。为此,我需要知道是否正在按下任何光标键。我试图覆盖ProcessCmdKey但没有成功。

任何提示/想法如何实现?

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
     }
  }

1 个答案:

答案 0 :(得分:1)

这有效!

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;
            }
        }
    }
}