在我的C#應用程序中,我有一個帶助記符的標籤(例如& Path)和一個按鈕。當用戶按下標籤的助記符時(例如[Alt]然後[P]),我想提高ButtonClick事件。但我還沒有發現任何標籤事件來處理這種情況。使用按鈕的OnFocus事件不是一個選項,因爲用戶可以使用[Tab]鍵導航。如何使用標籤的助記符來提高ButtonClick事件?
那麼有沒有辦法實現我想要的?
在此先感謝。
在我的C#應用程序中,我有一個帶助記符的標籤(例如& Path)和一個按鈕。當用戶按下標籤的助記符時(例如[Alt]然後[P]),我想提高ButtonClick事件。但我還沒有發現任何標籤事件來處理這種情況。使用按鈕的OnFocus事件不是一個選項,因爲用戶可以使用[Tab]鍵導航。如何使用標籤的助記符來提高ButtonClick事件?
那麼有沒有辦法實現我想要的?
在此先感謝。
,或者你可以只用一些與垃圾p
開始命名您的按鈕,然後把&
之前吧, alt + p
將觸發btn_Click
事件處理程序
編輯: 什麼這樣的事情:)
關鍵是,按鈕文本是「.. 「。 – 2011-04-20 09:40:42
@Dmitry:我編輯了我的文章 – 2011-04-20 09:44:43
爲什麼選擇投票? – 2011-04-20 09:48:48
你沒有指定項目(的WinForms/WPF)的類型,但我認爲解決方案將所有這類型是一樣的:
你應該設置你的形式爲true KeyPreview
和檢查按鍵在KeyUp
事件處理程序nelow :
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.P && e.Alt == true)
{
MessageBox.Show("Got it");
}
}
在此示例中,你會得到的消息框Alt + P的情況下,按下
他需要'Alt'鍵,我猜 – 2011-04-20 09:33:41
@ Rami.Shareef:這個樣本不夠,我編輯了我的ansewr,所以現在它的Alt鍵:) – 2011-04-20 09:40:31
@Anton:我喜歡那個:) – 2011-04-20 09:45:56
口訣在標籤上只給重點有下一個TabIndex
控制,這就是它所做的一切。你不能用它直接調用任何東西(比如按鈕的點擊事件)。
您可以使用此行爲的知識來模擬您想實現的目標。這個想法是在您的表單上放置一個輕量級,可調焦的控件,該控件有一個TabIndex
,緊跟在標籤後面,但位於不可見的位置(如超出左上角)。然後在隱藏的控件的焦點事件上做你想做的事情。
這是一個完整的獨立示例。在這種情況下,隱藏的控件將是一個複選框。
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyForm : Form
{
public MyForm()
{
targetLabel = new Label()
{
Text = "&Label",
TabIndex = 10,
AutoSize = true,
Location = new Point(12, 17),
};
// you don't need to keep an instance variable
var hiddenControl = new CheckBox()
{
Text = String.Empty,
TabIndex = 11, // immediately follows target label
TabStop = false, // prevent tabbing to control
Location = new Point(-100, -100), // put somewhere not visible
};
hiddenControl.GotFocus += (sender, e) =>
{
// simulate clicking on the target button
targetButton.Focus();
targetButton.PerformClick();
};
targetButton = new Button()
{
Text = "&Click",
TabIndex = 20,
AutoSize = true,
Location = new Point(53, 12),
};
targetButton.Click += (sender, e) =>
{
MessageBox.Show("Target Clicked!");
};
dummyButton = new Button()
{
Text = "&Another Button",
TabIndex = 0,
AutoSize = true,
Location = new Point(134, 12),
};
dummyButton.Click += (sender, e) =>
{
MessageBox.Show("Another Button Clicked!");
};
this.Controls.Add(targetLabel);
this.Controls.Add(hiddenControl);
this.Controls.Add(targetButton);
this.Controls.Add(dummyButton);
}
private Label targetLabel;
private Button targetButton;
private Button dummyButton;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
我明白你的觀點。我應該說好主意。 – 2011-04-20 10:23:58
@Dmitry:添加示例。 – 2011-04-20 10:37:38
您是否嘗試設置標籤的OnClick事件並在那裏調用按鈕單擊? – Gabriel 2011-04-20 09:31:21
是的,但助記符不會引發標籤的OnClick事件。 – 2011-04-20 09:35:12
是的,你是對的,助記符不會引起OnClick事件 – Gabriel 2011-04-20 09:37:23