如何在 C# 中制作按键表单事件

How to make a keypress form event in C#

我正在尝试在表单上创建一个 KeyPress 事件,但在这一行中出现错误 MainWindow.KeyPress = new KeyPressEventArgs(Form_KeyPress);,我阅读了有关 C# 事件的 Microsoft 文档,但我不明白.

C# 中是否存在 Java 中的侦听器?

我的代码:

class PracticeEvent
{
    static void Main(String[] args)
    {
        Form MainWindow = new Form();
        MainWindow.Text = "Practice";
        MainWindow.MaximizeBox = false;
        MainWindow.MinimizeBox = false;
        MainWindow.FormBorderStyle = FormBorderStyle.FixedSingle;
        MainWindow.StartPosition = FormStartPosition.CenterScreen;
        MainWindow.Size = new Size(1000, 700);
        MainWindow.KeyPreview = true;
        MainWindow.KeyPress = new KeyPressEventArgs(Form_KeyPress); 

        MainWindow.ShowDialog();

    }

    private void Form_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if(e.KeyCode == Keys.A){
            MessageBox.Show("You pressed the A key.");
        }
    }

}

您的主要方法是静态的,您的事件处理程序不是。您需要为它提供一个对象引用,这就是错误消息试图说明的内容。另一个错误是您正在分配而不是附加处理程序,为此使用 += 运算符。

具体来说,更改此行:

MainWindow.KeyPress = new KeyPressEventArgs(Form_KeyPress);

成为

var instance = new PracticeEvent();
MainWindow.KeyPress += instance.Form_KeyPress;

您的代码中有几个错误。

MainWindow.KeyPress = new KeyPressEventArgs(Form_KeyPress);

1) KeyPressKeyPressEventHandler 类型。不是 KeyPressEventArgs。在 C# 中,调用 ...EventArgs 的 classes 通常用作包含有关引发事件的数据的特殊对象,它们继承自 EventArgs 系统 class。而调用 ...EventHandlers 的 classes 通常是为委托定义包装器并调用事件。

2) 所以 KeyPress 是事件。如果您想订阅此事件,您应该使用 += 运算符。您要指定为处理程序的方法应具有签名 void(object, KeyPressEventArgs)。事件的典型签名是 void(object, ...EventArgs)

private void Form_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)

3) 正如我所说,此方法的签名错误(KeyPressEventArgs 而不是 KeyEventArgs)。

4) 应该是static。您不能在静态方法中使用非静态 class 成员。

因此您的代码应如下所示:

    class PracticeEvent
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            Form MainWindow = new Form();
            MainWindow.Text = "Practice";
            MainWindow.MaximizeBox = false;
            MainWindow.MinimizeBox = false;
            MainWindow.FormBorderStyle = FormBorderStyle.FixedSingle;
            MainWindow.StartPosition = FormStartPosition.CenterScreen;
            MainWindow.Size = new Size(1000, 700);
            MainWindow.KeyPreview = true;
            MainWindow.KeyPress += Form_KeyPress;
            MainWindow.ShowDialog();
        }

        private static void Form_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == 'a')
            {
                MessageBox.Show("You pressed the A key.");
            }
        }
    }

在 C# 中使用侦听器不是好的做法,但某些框架使用它。通常使用事件和回调。

还有我最后的建议。也许您想使用 KeyDown 事件? KeyPress 用于处理字符输入。