簡體   English   中英

如何在 C# 中創建按鍵表單事件

[英]How to make a keypress form event in C#

我正在嘗試在表單上創建 KeyPress 事件,但在這一行中我收到一個錯誤MainWindow.KeyPress = new KeyPressEventArgs(Form_KeyPress); ,我閱讀了有關 C# 事件的 Microsoft Docs,但我不明白。

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) KeyPress具有KeyPressEventHandler類型。 不是KeyPressEventArgs 在 C# 中,稱為...EventArgs類通常用作包含有關引發事件的數據的特殊對象,並且它們是從EventArgs系統類繼承的。 調用...EventHandlers類通常為委托和調用的事件定義包裝器。

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 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用於處理字符輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM