簡體   English   中英

如何在WPF中從用戶讀取自定義鍵盤快捷鍵?

[英]How do I read custom keyboard shortcut from user in WPF?

在我的應用程序中,我想讓用戶自定義鍵盤快捷鍵,就像在Visual Studio的鍵盤選項中一樣。 用戶可以聚焦空白文本框,然后鍵入他想要分配給命令的任何快捷方式。

我最接近它的工作是訂閱TextBox.PreviewKeyDown事件,將其設置為處理以防止在文本框中輸入實際文本。 然后我忽略與修飾鍵相關聯的KeyDown事件(是否有更簡潔的方法來確定Key是否是修飾鍵?)。

// Code-behind
private void ShortcutTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // The text box grabs all input
    e.Handled = true;

    if (e.Key == Key.LeftCtrl || 
        e.Key == Key.RightCtrl || 
        e.Key == Key.LeftAlt ||
        e.Key == Key.RightAlt || 
        e.Key == Key.LeftShift ||
        e.Key == Key.RightShift)
        return;

    string shortcutText = "";
    if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
        shortcutText += "Ctrl+";
    if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
        shortcutText += "Shift+";
    if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
        shortcutText += "Alt+";
    _ShortcutTextBox.Text = shortcutText + e.Key.ToString();

}

以上適用於以Ctrl和Ctrl + Shift開頭的任何快捷方式,但對於任何Alt快捷方式都失敗。 當我按下包含Alt的快捷方式時,e.Key始終設置為Key.System

如何記錄用戶的Alt快捷鍵? 是否有更好,更健壯的方式來記錄用戶的快捷方式?

如果Key屬性設置為Key.System ,則使用SystemKey屬性:

private void ShortcutTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // The text box grabs all input.
    e.Handled = true;

    // Fetch the actual shortcut key.
    Key key = (e.Key == Key.System ? e.SystemKey : e.Key);

    // Ignore modifier keys.
    if (key == Key.LeftShift || key == Key.RightShift
        || key == Key.LeftCtrl || key == Key.RightCtrl
        || key == Key.LeftAlt || key == Key.RightAlt
        || key == Key.LWin || key == Key.RWin) {
        return;
    }

    // Build the shortcut key name.
    StringBuilder shortcutText = new StringBuilder();
    if ((Keyboard.Modifiers & ModifierKeys.Control) != 0) {
        shortcutText.Append("Ctrl+");
    }
    if ((Keyboard.Modifiers & ModifierKeys.Shift) != 0) {
        shortcutText.Append("Shift+");
    }
    if ((Keyboard.Modifiers & ModifierKeys.Alt) != 0) {
        shortcutText.Append("Alt+");
    }
    shortcutText.Append(key.ToString());

    // Update the text box.
    _ShortcutTextBox.Text = shortcutText.ToString();
}

我將左右Windows鍵添加到修改器列表中,因為當從終端服務器會話中鍵入復雜( Ctrl+Shift+Alt )組合鍵時,它們有時會出現在快捷鍵名稱中。 但它們從未出現在Keyboard.Modifiers ,因為它們是為全局快捷方式保留的,所以我不會在那里處理它們。

我還使用StringBuilder來避免創建太多的string實例。

此解決方案適用於除Shift+Alt之外的任何組合Shift+Alt (在這種情況下不會看到Alt修飾符)。 這可能是我的終端服務器環境的工件,所以你的里程可能會有所不同。

最后,我在窗口中添加了一個_File菜單以查看會發生什么,並且Alt+F快捷鍵在到達菜單之前被文本框有效地捕獲,這似乎是您想要的。

你好
如果You used WPF-Command在應用程序中You used WPF-Command ,則可以使用:

<Window.InputBindings>
  <KeyBinding Command="YourCommnad"
              Gesture="CTRL+C" />
</Window.InputBindings>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM