C# 按鍵觸發事件處理


這次範例以點擊F1來觸發Button_click為例
首先要在Form的屬性中找到"KeyPreview"屬性,將其設置為true
然後添加程式碼

private bool isSpaceKeyPressed = false;//確定按一次只執行一次動作

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F1 && !isSpaceKeyPressed)
    {
        isSpaceKeyPressed = true;

        // 在這裡執行按鈕的事件處理邏輯,也可以替換其他事件
        button1.PerformClick();
    }
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F1)
    {
        isSpaceKeyPressed = false;
    }
}

要注意盡量不要用會觸發其他東西的按鍵
不然就算給他判斷還是會重複執行
最後還有一個重要的步驟
要將視窗的KeyDown事件與剛剛建立的事件綁定

public Form1()
{
    InitializeComponent();
    this.KeyDown += Form1_KeyDown;
    this.KeyUp += Form1_KeyUp;
}

上面這種方法會有一個問題
當Focus在其他控件上時按鍵就不會觸發
所以可以將全部改成複寫ProcessCmdKey

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1) // 按下 F1 鍵
    {
        // 執行您想要的操作
        return true; // 表示按鍵已被處理
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

這樣一來不用限制在哪裡按鍵
也較為簡潔

#C# #Winform







你可能感興趣的文章

The introduction and difference between class component and function component in React

The introduction and difference between class component and function component in React

Print lots of stars

Print lots of stars

1 - 非同步之認識Promise

1 - 非同步之認識Promise






留言討論