Dialog window `KeyDown` Event Handler not hitting (C#)

1k views Asked by At

I have a KeyDown event handler (created by Visual Studio) for my dialog to close the window:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape)
    {
        this.DialogResult = false;
        this.Close();
    }
}

When I'm in the program and press the Escape key, the dialog goes to the back of the main screen instead of closing it. I put a break point in at the function, and it never hits.

Has this happened to anyone before? Does anyone know of a solution?

1

There are 1 answers

0
Kirill Osenkov On

I think this answer may help: https://stackoverflow.com/a/980518/37899

Basically, if your dialog is completely empty and there isn't a focused control, the KeyDown and Up events will not be raised. For some reason they only get raised when there's at least one focusable control in the window and it's focused.