簡體   English   中英

在C#中按下“ Enter鍵”的自定義事件

[英]a custom event for pressing the 'Enter key' in C#

我有一個帶有一些控件和一個文本框的UserControl,當要在該文本框上按Enter鍵時,我想執行一些步驟,我在UserControl中有以下代碼:

public event EventHandler TextBoxKeyPressed
{
    add { textBox.KeyPressed+=value; }
    remove { textBox.KeyPressed-=value; }
}

在我的主要形式中,我有很多這樣的控件,對於每個控件,我應該檢查是否按下了鍵,如果是Enter鍵,請執行以下步驟。

有什么方法可以創建自定義事件來檢查UserControl中按下的鍵,如果是Enter鍵,則觸發該事件?

更新:每個自定義控件在KeyPresssd事件上可能具有不同的過程

當然,您可以添加一個EnterPressed事件,並在檢測到按下Enter鍵時將其觸發:

public partial class UserControl1 : UserControl {
    public event EventHandler EnterPressed;

    public UserControl1() {
        InitializeComponent();
        textBox1.KeyDown += textBox1_KeyDown;
    }

    protected void OnEnterPressed(EventArgs e) {
        var handler = this.EnterPressed;
        if (handler != null) handler(this, e);
    }

    void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyCode == Keys.Enter) {
            OnEnterPressed(EventArgs.Empty);
            e.Handled = e.SuppressKeyPress = true;
        }
    }
}

該事件沒有改變,它仍然是正常的按鍵事件。 如果鍵是回車鍵,則只在其中執行預期的操作。 像這樣:

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        // the enter key was pressed
    }
}

暫無
暫無

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

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