5

Escape キーで WPF ウィンドウを閉じたい。ただし、その Escape キーを使用できるコントロールがある場合、ウィンドウを閉じたくありません。ESC キーが押されたときに WPF ウィンドウを閉じる方法には複数の解決策があります。例えば。WPF Button.IsCancel プロパティはどのように機能しますか?

ただし、このソリューションは、Escape キーを使用できるアクティブなコントロールがあるかどうかに関係なく、ウィンドウを閉じます。

たとえば。DataGrid を持つウィンドウがあります。dataGrid の列の 1 つがコンボボックスです。ComboBox を変更して Escape を押すと、コントロールはコンボボックスの編集から抜け出すはずです (通常の動作)。Escape をもう一度押すと、ウィンドウが閉じます。大量のカスタム コードを記述するのではなく、一般的なソリューションが必要です。

C# で解決策を提供できれば、それは素晴らしいことです。

4

3 に答える 3

3

KeyDownイベントの代わりにイベントを使用する必要がありますPreviewKeyDown。のいずれかの子がWindowイベントを処理する場合、イベントはウィンドウ (下PreviewKeyDownからのトンネルWindow) までバブルアップされないため、イベント ハンドラーは呼び出されません。

于 2010-04-19T21:43:40.290 に答える
1
class Commands
{
    static Command
    {
        CloseWindow = NewCommand("Close Window", "CloseWindow", new KeyGesture(Key.Escape));
        CloseWindowDefaultBinding = new CommandBinding(CloseWindow,
            CloseWindowExecute, CloseWindowCanExecute);
    }

    public static CommandBinding CloseWindowDefaultBinding { get; private set; }
    public static RoutedUICommand CloseWindow { get; private set; }

    static void CloseWindowCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = sender != null && sender is System.Windows.Window;
        e.Handled = true;
    }
    static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
    {
         ((System.Windows.Window)sender).Close();
    }
}

// In your window class's constructor. This could also be done
// as a static resource in the window's XAML resources.
CommandBindings.Add(Commands.CloseWindowDefaultBinding);
于 2011-08-16T12:38:26.497 に答える
1

もっと簡単な方法があるかもしれませんが、ハッシュ コードを使用して実行できます。Keys.Escape も別のオプションですが、何らかの理由で機能しないことがあります。言語を指定しなかったため、VB.NET の例を次に示します。

Private Sub someTextField_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles someTextField.KeyPress

    If e.KeyChar.GetHashCode = 1769499 Then ''this number is the hash code for escape on my computer, do not know if it is the same for all computers though.
        MsgBox("escape pressed") ''put some logic in here that determines what ever you wanted to know about your "active control"
    End If

End Sub
于 2010-04-19T02:59:58.970 に答える