C# WinForm給Button按鈕或其它控制項添加快速鍵響應

來源:互聯網
上載者:User

標籤:winform   style   ar   使用   sp   for   strong   on   代碼   

就在這介紹三種添加快速鍵的方式。

第一種Alt + *(按鈕快速鍵)

在大家給button、label、menuStrip等控制項設定Text屬性時在名字後邊加&鍵名就可以了,比如button1.text= "確定(&A)"。就會有快速鍵了,這時候按Alt+A就可以執行按鈕單擊事件。

 

第二種Ctrl+*及其他按鍵組合  

在WinForm中設定要使用按鍵組合的表單的KeyPreview(向表單註冊鍵盤事件)屬性為True;然後使用表單的KeyDown事件(在首次按下某個鍵時發生).  

執行個體代碼:  

private void 表單名字_KeyDown(object sender, KeyEventArgs e)  

{   

if (e.KeyCode == Keys.F && e.Control)

{  

button1.PerformClick(); //執行單擊button1的動作

}    

}    

註:大家可以看一下 ”Keys”的枚舉參數,以實現自己需要 

當使用Ctrl + *快速鍵時,對於焦點在可寫的控制項(如TextBox)上時,可能會將* 索引值同時輸入,則需要加另一句話將Handled設定為true,以取消 KeyPress 事件

如下代碼:

private void ***_KeyDown(object sender, KeyEventArgs e)  

{    

if (e.KeyCode == Keys.F && e.Control)  

e.Handled = true; //將Handled設定為true,指示已經處理過KeyPress事件   

button1.PerformClick();    

}    

}  

第三種 表單的keydown事件響應斷行符號添加快速鍵

private void 表單名稱_KeyDown(object sender, KeyEventArgs e)  

{  

if (e.KeyCode == Keys.Enter)  

{  

Button_Click(sender, e);  

 }  

}  

C# WinForm給Button按鈕或其它控制項添加快速鍵響應

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.