如何為沒有文本的 Windows 表單按鈕設定鍵盤快捷鍵字符?
我有一個 Windows 表單應用程式,其中包含一些帶有影像但沒有文本的按鈕。通常對于按鈕,快捷方式是用與號字符 (&) 指定的。但是沒有文字的時候怎么辦?
我知道有一些技巧,例如引導空格將文本向右或向下推。或者使用字體、前景色等。但我不喜歡這樣的技巧,因為它們有時會適得其反。
我應該考慮通過表單的 Key 事件處理所有控制元件的快捷方式嗎?這將如何排序選擇了哪個控制元件?表單鍵事件在發送到控制元件的鍵事件之前是否通過表單過濾?如果我走這條路,我不知道該怎么辦。
uj5u.com熱心網友回復:
我是否應該考慮通過 Form 的 Key 事件處理所有控制元件的快捷方式?
您當然可以,在您的表單中覆寫ProcessCmdKey( )。正如您在檔案中所讀到的那樣,它是為此而設計的(提供對主選單命令鍵和 MDI 加速器的額外處理)
要將 Button 與 Keys 的按位組合相關聯(Windows 表單Keys列舉器用[Flags]屬性修飾),您可以使用map,通常是 Dictionary 將 Key 與其他內容相關聯。
在這種情況下,它可以是按鈕控制元件或操作。例如:
private Dictionary<Keys, Button> accelerators = null;
protected override void OnLoad(EventArgs e) {
accelerators = new Dictionary<Keys, Button>() {
[Keys.Alt | Keys.A] = someButton,
[Keys.Alt | Keys.Control | Keys.B] = otherButton
};
base.OnLoad(e);
}
在ProcessCmdKey覆寫中,測驗地圖(字典)是否包含按下的鍵組合,如果匹配,則引發關聯 Button 的 Click 事件:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (accelerators.ContainsKey(keyData)) {
accelerators[keyData].PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
VB.Net 版本(因為它被標記):
Private accelerators As Dictionary(Of Keys, Button) = Nothing
Protected Overrides Sub onl oad(e As EventArgs)
accelerators = New Dictionary(Of Keys, Button)() From {
{Keys.Alt Or Keys.A, someButton},
{Keys.Alt Or Keys.Control Or Keys.B, otherButton}
}
MyBase.OnLoad(e)
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If accelerators.ContainsKey(keyData) Then
accelerators(keyData).PerformClick()
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
uj5u.com熱心網友回復:
我就是這樣做的。
將表單設定KeyPreview為true捕獲鍵。
然后檢查KeyDown表單上的事件鍵并觸發button1.PerformClick();
public Form1()
{
InitializeComponent();
KeyPreview = true;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("you pressed Ctrl S");
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
{
button1.PerformClick();
}
}
uj5u.com熱心網友回復:
希望這可以幫到你。
將您的表單 KeyPreview 屬性設定為 true。
訂閱表單的 KeyDown 事件如下:
this.KeyDown = new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
處理 Form 的 KeyDown 事件如下:
private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.S) MessageBox.Show("Ctrl S pressed!"); }
完整代碼:
this.KeyDown = new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
MessageBox.Show("Ctrl S pressed!");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522156.html
