I need to highlight the current key pressed in my C# application. To get the keyboard keys code during keyDown and keyUp events i tried returning the keycodes as

protected override void OnKeyDown(KeyEventArgs keyEvent) 
{ 
    // Gets the key code 
    lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString(); 
}

Other way i tried was to check if each key that i need is pressed

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Create a TextBox control.
            Button enterBtn = new Button();
            this.Controls.Add(enterBtn);
            enterBtn.KeyPress += new KeyPressEventHandler(keypressed);
        }

         private void keypressed(Object o, KeyPressEventArgs e)
         {
             // The keypressed method uses the KeyChar property to check 
             // whether the ENTER key is pressed. 
             // If the ENTER key is pressed, the Handled property is set to true, 
             // to indicate the event is handled.
             if (e.KeyChar == (char)Keys.Return)
             {
                 enterBtn.BackColor = Color.Purple;
                 e.Handled = true;
             }
         }

but still the button on Form1 did not highlighted. help please :(

Hi,
Set Form's KeyPreview property to True. Otherwise your handler won't be called. Then you can use KeyPress or KeyDown event.

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.