在我的C#应用程序中,我有一个带有助记符的标签(例如&Path)和一个按钮。我希望当用户按下标签的助记符(例如[Alt]然后[P])时触发ButtonClick事件。但我没有找到任何可以处理这种情况的标签事件。使用按钮的OnFocus事件不是一个选项,因为用户可能使用[Tab]键进行导航。
那么,有没有办法实现我想要的效果?
提前致谢。
那么,有没有办法实现我想要的效果?
提前致谢。
或者您可以给按钮命名以以字母 p
开头的名称,然后在它之前加上 &
,alt + p
将触发 btn_Click
事件处理程序。
编辑: 这样的东西怎么样 :)
标签上的助记符只会将焦点放在具有下一个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());
}
}
您没有指定项目类型(Winforms/WPF),但我认为所有这些类型的解决方案都是相同的:
您应该将表单上的KeyPreview
设置为true,并在KeyUp
事件处理程序中检查按下的键,如下所示:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.P && e.Alt == true)
{
MessageBox.Show("Got it");
}
}
Alt
键,我猜。 - Rami Alshareef