Dumbo
Dumbo

Reputation: 14112

Capturing KeyDown and KeyUp events for cursor keys

I want to move some graphics in a winfor application. To do this I need to know if any of the cursor keys are being pressed. I tried to override ProcessCmdKey but no success.

Any tips/ideas how to implement this?

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

Upvotes: 0

Views: 733

Answers (1)

Parimal Raj
Parimal Raj

Reputation: 20575

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

Upvotes: 1

Related Questions