问题
I'm experiencing some troubles using mnemonic keys in Windows Forms:
Simply having a form with a button, which uses ALT+s as the accelerator:
this.searchButton = new System.Windows.Forms.Button();
this.searchButton.Text = "&search";
The button action is executed by simply pressing "s" (without pressing the ALT key). I have checked some other applications, and the accelerator actions are only executed when the ALT key is pressed.
- Is this a .NET problem?
- How could address this issue?
Thanks in advance.
回答1:
This is normal behavior for .NET ("by design", they say).
Here is an article that should help with your issue - not simple or pretty to start out with, but once it's done, any shortcut keys you set up can be easily added:
Building Keyboard Accelerators into .NET Windows Forms Applications - Code Guru
Basically, this solution involves creating a class, loading a hash table, and overriding ProcessCmdKey to set up your own accelerator handler.
回答2:
You can alter this behavior by pasting this snippet into your form:
protected override bool ProcessDialogChar(char charCode) {
if ((Control.ModifierKeys & Keys.Alt) == Keys.None) return false;
return base.ProcessDialogChar(charCode);
}
Not 100% sure this won't have other side-effects, keyboard handling in Winforms is convoluted to put it mildly.
来源:https://stackoverflow.com/questions/8593892/accelerator-mnemonic-key-are-executed-without-pressing-alt-key