好的!我有一个解决方案可以在没有按下 Alt 但按下 Ctrl 的情况下为热键显示 _。
这是怎么做的:
动态按下键盘键的小代码:
//<summary>
//Function to Perform a Keyboard KeyPress.
//</summary>
void PressKey(Key KeyboardKey)
{
KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice,
Keyboard.PrimaryDevice.ActiveSource, 0, Key.LeftAlt);
args.RoutedEvent = Keyboard.KeyDownEvent;
InputManager.Current.ProcessInput(args);
}
添加和删除 HotKeyChar 的代码:
//<summary>
//Function to Append a HotKeyChar to a Content of a Control.
//</summary>
void AppendHotKeyChar(ContentControl Ctrl, int KeyIndex)
{
if (Ctrl.Content.ToString().Substring(KeyIndex, 1) != "_")
{
Ctrl.Content = "_" + Ctrl.Content;
}
}
//<summary>
//Function to Remove a HotKeyChar to a Content of a Control.
//</summary>
void RemoveHotKeyChar(ContentControl Ctrl, int KeyIndex)
{
if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_")
{
Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1);
}
}
Button Bt1 的 XAML 代码:
<Button x:Name="Bt1" Content="Button" HorizontalAlignment="Left" Margin="169,97,0,0" VerticalAlignment="Top" Width="75"/>
MainWindow 的Window.Loaded 事件代码(例如MainWindow1_Loaded):
PressKey(Key.LeftAlt);
MainWindow 的Window.KeyDown 事件代码(例如MainWindow1_KeyDown):
if (e.Key == Key.LeftCtrl)
{
AppendHotKey(Bt1, 0);
}
MainWindow 的Window.KeyUp 事件代码(例如MainWindow1_KeyUp):
if (e.Key == Key.LeftCtrl)
{
RemoveHotKey(Bt1, 0);
}
现在,当您启动应用程序时,Alt 将被动态按下一次。
现在每次你按下 Ctrl,你的Control.Content 将被附加一个_,所以HotKey 将出现下划线!
但要注意的是,您应该在没有 HotKeyChar '_' 的情况下创建 Control.Content,但保留一个 Index 以在其中添加您的 _。
但请记住,如果在您的应用中再次按下 Alt,代码将不再起作用。因此,您必须再次按 Alt 才能使代码正常工作!
附加和删除HotKeyChar 的最佳方法:
- 创建
List<KeyValuePair<int, Control>> 的实例以存储HotKeyChar 和Control 的Index。
- 现在在
KeyDown 事件中,只需循环遍历List<...> 中的KeyValuePair<...>..附加_。
- 再次在
KeyUp 事件中循环遍历KeyValuePair<...> 中的List<...>..删除_。
希望对您有所帮助!