1

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");
        }
    }
Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
Spr89
  • 81
  • 1
  • 9
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders May 05 '15 at 22:54
  • Sorry about that, will do – Spr89 May 05 '15 at 22:55
  • Take a look at http://stackoverflow.com/a/400325/49251, which may be of use. – DWright May 05 '15 at 22:56
  • 1
    Keyboard events are raised on the control with the focus. That's almost never the form if it has any controls. Implement shortcut keystrokes with ProcessCmdKey(), do consider using a menu so it is discoverable. – Hans Passant May 06 '15 at 07:55

2 Answers2

2

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.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
  • @ PiotrWolkowski, I would kiss you if i could. I read the link you provided but i dont understand it. More specifically, why my code wasnt working when the event handler generated the code to rais, fire, and trigger the event? – Spr89 May 06 '15 at 04:25
0

Did you subscribe your handler (Color_KeyDown) to an event such as PreviewKeyDown? I see you hooked up directions_Click to listen for mouse clicks on your ToolStripMenuItem called "directions" control, but from your code, I don't see where you're listening for key events.

Try adding a line similar to:

myWinFormsControl.PreviewKeyDown += Color_KeyDown;

where myWinFormsControl is the window or control you want to invoke your handler whenever a keypress event fires. Note: make sure you give the control input focus when testing (for example if it's a textbox, it won't fire a keypress event unless the text cursor is inside prior to pressing the key).

Another helpful trick if you're using visual studio is you can select a control while in design view and open the properties pane and click the little lightning bolt icon to see all the see all the available events for that control. You can also double click inside one of the empty sells to add a new event handler. (see here for more details)

Quick example of getting keypress events from a textbox in winforms:

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        TextBox someTextBox = new TextBox();
        someTextBox.PreviewKeyDown += someTextBox_PreviewKeyDown;

        Form myMainWindow = new Form();
        myMainWindow.Controls.Add(someTextBox);

        Application.Run(myMainWindow);
    }

    static void someTextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs 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");
        }
    }
}

and to just catch at the form level (aka as long as the window has input focus):

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form myMainWindow = new Form();
        myMainWindow.PreviewKeyDown += myForm_PreviewKeyDown;

        Application.Run(myMainWindow);
    }

    static void myForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs 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");
        }
    }
}
Community
  • 1
  • 1
Beau C.
  • 36
  • 4
  • Where is it supposed to go. Ive tried my main program and the designer but no go – Spr89 May 05 '15 at 23:30
  • I add this.KeyDown += new KeyEventHandler(Color_KeyDown); to the program, and still no go :'-( – Spr89 May 05 '15 at 23:36
  • I edited my response to give you a quick demo of how to make it work with a textbox. If you give the textbox input focus (aka click in it) and press Ctrl+L or Shift+A you'll see the corresponding messageboxes. To answer your question of "Where is it supposed to go", it needs to go on whomever you want to listen to key input on. It could be anything from your main Form control all the way down to a very specific child control of that Form. – Beau C. May 05 '15 at 23:45
  • Im not trying to use this on a text box, im trying to use this on the whole form. there isnt a single text box on the form. just radio buttons and output labels – Spr89 May 06 '15 at 00:50
  • The textbox was just an example I used for demonstration purposes, I wasn't aware of the child controls of your form. I edited my response with another version of my example, this time capturing keypresses at the form level... as long as your window is in focus, Ctrl+L and Shift+A will show your message boxes. :) – Beau C. May 06 '15 at 01:11
  • Try this in Visual Studio: 1. Find your main form's file in the solution explorer and double-click to open designer view (should open a tab in Visual Studio .cs [Design]. 2. Select your form (for example by clicking on form's title bar). 3. Press the F4 key to open the properties window. 4. Click the lightning bolt icon with the tooltip: "Events". 5. Locate the PreviewKeyDown item in the table that appears. 6. Double-left-click in the cell to the right of PreviewKeyDown (will most likely be empty) to add a new handler. 7. Paste your message box code in the method that appears. – Beau C. May 06 '15 at 01:30