如何使Visual C#studio识别键输入 [英] How to make Visual C# studio recognize key input

查看:88
本文介绍了如何使Visual C#studio识别键输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }
}
}

推荐答案

在表单描述中编写方法不会将其链接到有人按下键时触发的事件.在设计器内部(该视图提供表单的预览并允许您对其进行拖放),在属性面板中,顶部有一个闪电图标.如果按下它,它将列出该表单中公开的所有事件.您可以双击KeyDown事件,它将自动创建正确的方法并添加:

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

在设计器自动生成的.Designer.cs文件中. 仅当表单内部的控件具有焦点时,才需要KeyPreview.可能是这种情况.

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.

这篇关于如何使Visual C#studio识别键输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆