简体   繁体   中英

How to make Visual C# studio recognize key input

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)
    {

    }
}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM