Search code examples
c#winformskeypresskeyboard-events

How can i capture Key press events?


I'm trying to have 2 different message box display when "Ctrl+l" is pressed and another when "Shift+A" is pressed as well. I have everything done but when i press these button while the program is running, nothing happens. I'm not sure what i have done wrong.

My code as follows:

public Color()
    {
        InitializeComponent();

       ContextMenuStrip s = new ContextMenuStrip();
       ToolStripMenuItem directions = new ToolStripMenuItem();
       directions.Text = "Directions";
       directions.Click += directions_Click;
       s.Items.Add(directions);
       this.ContextMenuStrip = s;
       this.KeyDown += new KeyEventHandler(Color_KeyDown);//Added
    }
    void directions_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Just click on a color chip to see the translation");
    }
    //Keypress
    private void Color_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.L && (e.Control))
        {
            MessageBox.Show("You can choose from four different languages by clicking on the radio buttons");
        }
        else if (e.KeyCode == Keys.A && (e.Shift))
        {
            MessageBox.Show("This is version 1.0");
        }
    }

Solution

  • If you want to capture command keys in your form or control you have to override the ProcessCmdKey method. In your form use this code

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Shift | Keys.A))
            {
    
            }
            else if (keyData == (Keys.Control | Keys.I))
            {
    
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
    

    Here you can find more about processing command keys.