How to Close a Window in WPF on a escape key

前端 未结 4 2091
青春惊慌失措
青春惊慌失措 2020-12-24 10:49

Possible Duplicate:
How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

4条回答
  •  Happy的楠姐
    2020-12-24 11:38

    Option 1

    Use Button.IsCancel property.

    
    

    When you set the IsCancel property of a button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key.

    However, this works properly only for Dialogs.

    Option2

    You add a handler to PreviewKeyDown on the window if you want to close windows on Esc press.

    public MainWindow()
    {
        InitializeComponent();
    
        this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
    }
    
    private void HandleEsc(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
            Close();
    }
    

提交回复
热议问题