3

I'm quite new to C# and programming in general. Basically my problem is that I am trying to make a simple code, which uses key input, but when I run (debug) the program, it doesn't recognize any key input at all. KeyPreview is set to true, but it still seems not to do anything. Could you please tell me what am I doing wrong? Thank you.

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public List<string> list = new List<string>();
        public Form1()
        {
            InitializeComponent();
            KeyPreview = true;
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F3)
        {
            list.Add("OMG!");
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(list[0]);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
}
  • 1
    Is "Form1_KeyDown" correctly linked to your form's event? Did you create it by hand or from the designer? You don't even need KeyPreview for trapping keyboard input. – LightStriker Oct 20 '12 at 13:47
  • Thank you for your answer. Could you please explain what do you mean by "correctly linked to your form's event"? And yes, I've just written it into the form code. Thank you – user1761590 Oct 20 '12 at 13:51
  • @user1761590 you can also use `protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); }` – L.B Oct 20 '12 at 13:58

1 Answers1

1

Writing a method inside the form description doesn't link it to the event that is fired when someone press a key. Inside the Designer (the view that gives a preview of your form and allow you to drop control on it), in the property panel, there's a lightning icon at the top. If you press it, it lists all the event exposed in that form. You can double click on KeyDown event, and it will create the right method automaticly and it will add:

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

Inside the .Designer.cs file that is automatically generated by the designer. You will need KeyPreview only if a control inside your form has focus... Which is probably the case.

LightStriker
  • 19,738
  • 3
  • 23
  • 27