问题
I'm developing a large line of business app with C# and WPF. Our standard is to include accelerator keys for buttons on all forms (Save, Cancel, Search, etc.). I've recently noticed that when a form is loaded, the accelerator key is active even when the user does not press the "Alt" key. For example, our Search button uses "Alt-H" as the accelerator, but the user can initiate a search by simply pressing "H". I'm using the standard "_" in the button content to create the accelerator key.
<Button Content="Searc_h"/>
Has anyone else noticed this behavior and has anyone found a suitable workaround that requires the "Alt" key to be pressed?
回答1:
This is standard behaviour for accelerator keys on Windows whenever no text input is focused. Please don’t break it, just leave it in.
You can check this yourself. Press Win+R to bring up the "Run..." dialog, then Tab so one of the buttons is focused, then press "B". The "Browse" button will get activated.
This is also why you can answer those MessageBox prompts with a simple Y/N (instead of Alt+Y / Alt+N).
回答2:
Don't put the underscore in at all, then add this to the window.
<Window.InputBindings>
<KeyBinding Command="Help" Key="H" Modifiers="Alt"/>
</Window.InputBindings>
回答3:
This article on Sara Ford's Weblog discusses this phenomenon.
A commenter mentions this as a solution:
"If you're writing an application and you don't like this behavior, look up WM_CHANGEUISTATE and specifically the UISF_HIDEFOCUS flag."
回答4:
Menu and ToolBar mnemonics work without pressing Alt key in WPF. This is the microsoft standard. Refer the this link http://social.msdn.microsoft.com/Forums/en/wpf/thread/14f6f49f-0027-471b-b68c-e7f6ba012012
回答5:
Actually, the Command pattern in WPF allows you more granular control over what keyboard shortcuts are allowed. It goes a step further than the "_" in your button text.
Check the following link for more information:
http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands
Edit: previous link was dead - provided a new link.
-Doug
来源:https://stackoverflow.com/questions/696973/wpf-accelerator-keys-like-visual-studio