Trying for the life of me to figure this out, but I can't seem to make sense of it.

I found some code that demonstrates how keyboard events are handled, but it doesn't work when I have a textbox on my form. When the textbox has focus, the event does not trigger. However, the only other code I found online will make events trigger even when the program itself has no focus. I don't want that. I just want it to work no matter where I hit the buttons in the form.

Basically, I want to be able to be able to make standard keyboard shortcuts like CTRL+O to open a file.

This is what I have now:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.KeyUp += new KeyEventHandler(Form1_KeyUp);
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            MessageBox.Show(e.KeyCode.ToString(), "Your input");
        }
    }
}

Recommended Answers

All 9 Replies

In the designer, or in your Form1 constructor, set the KeyPreview property to true:

public Form1() {
    InitializeComponent();
    this.KeyUp += new KeyEventHandler(Form1_KeyUp);
    this.KeyPreview = true;
}

Thanks!

I don't suppose you could explain why it was needed? Just curious.

The form will let the control handle the event first, and if the control handles it, the form ignores it. By setting KeyPreview to true you tell the form to process the event first, then pass it on to the control if it wasn't handled.

Interesting you say that, though... I tested it out, and the character appeared in the textbox even though the popup appears... so it's not quite doing what you say.

I guess another question on the subject I can ask is whether or not I should use KeyDown or Keypress... I noticed that they handle special keys differently.

It is doing what I said, you don't have code in your event letting the system know that they keyup was handled.

Then how do I tell my event block to not pass it to the form?

using e.Handled = true; causes the textbox form's event handler to ignore the key event, but it still types the character into the box. In the case of ctrl-o, I get a beep. Is there a way to get the key to not even reach the textbox at all?

Nevermind. I discovered that the tool strip item has a shortcut key property... so that did what I want, and prevented the beep from happening.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.