如何让Visual C#studio识别按键输入

如何让Visual C#studio识别按键输入,c#,text,input,C#,Text,Input,一般来说,我对C#和编程相当陌生。基本上,我的问题是,我试图编写一个简单的代码,它使用键输入,但当我运行(调试)程序时,它根本无法识别任何键输入。KeyPreview设置为true,但它似乎仍然没有任何作用。你能告诉我我做错了什么吗?多谢各位 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using Syst

一般来说,我对C#和编程相当陌生。基本上,我的问题是,我试图编写一个简单的代码,它使用键输入,但当我运行(调试)程序时,它根本无法识别任何键输入。KeyPreview设置为true,但它似乎仍然没有任何作用。你能告诉我我做错了什么吗?多谢各位

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

    }
}
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
命名空间Windows窗体应用程序1
{
公共部分类Form1:Form
{
公共列表=新列表();
公共表格1()
{
初始化组件();
KeyPreview=true;
}
私有void Form1\u KeyDown(对象发送方,KeyEventArgs e)
{
if(e.KeyCode==Keys.F3)
{
添加(“OMG!”);
}
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
MessageBox.Show(列表[0]);
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
}
}

在表单描述中写入方法不会将其链接到某人按键时触发的事件。在设计器内部(提供窗体预览并允许您在其上放置控件的视图),在属性面板的顶部有一个闪电图标。如果您按下它,它将列出以该形式显示的所有事件。您可以双击KeyDown事件,它将自动创建正确的方法,并添加:

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
在设计器自动生成的.Designer.cs文件中。
只有当窗体中的控件具有焦点时,才需要KeyPreview。。。可能是这样。

是否将“Form1\u KeyDown”正确链接到表单的事件?你是手工还是设计师设计的?您甚至不需要KeyPreview来捕获键盘输入。谢谢您的回答。请您解释一下“正确链接到表单事件”是什么意思?是的,我刚刚把它写进表单代码中。感谢you@user1761590您还可以使用
protectedoverridevidiononkeydown(KeyEventArgs e){base.OnKeyDown(e);}