[英]How to make Visual C# studio recognize key input
I'm quite new to C# and programming in general. 我对C#和一般编程很陌生。 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.
KeyPreview设置为true,但是它似乎仍然不做任何事情。 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:
您可以双击KeyDown事件,它将自动创建正确的方法并添加:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
Inside the .Designer.cs file that is automatically generated by the designer. 在设计器自动生成的.Designer.cs文件中。 You will need KeyPreview only if a control inside your form has focus... Which is probably the case.
仅当表单内部的控件具有焦点时才需要KeyPreview ...可能是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.