【问题标题】:How to make Visual C# studio recognize key input如何让 Visual C# studio 识别按键输入
【发布时间】:2012-10-20 13:45:08
【问题描述】:

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

    }
}
}

【问题讨论】:

  • “Form1_KeyDown”是否正确链接到您的表单事件?你是手工制作的还是设计师设计的?您甚至不需要 KeyPreview 来捕获键盘输入。
  • 感谢您的回答。您能否解释一下“正确链接到您的表单事件”是什么意思?是的,我刚刚将它写入表单代码。谢谢
  • @user1761590 你也可以使用protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); }

标签: c# text input


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2014-12-02
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多