Fraze
Fraze

Reputation: 948

Window Closing Event and KeyPress

<Window Closing="Window_Closing"></Window>

Assuming keys are used to close the window. Is there a way to determine which keys were used?

I know you can with the KeyDown event but need to do so in the Closing event.

Thank you!

Upvotes: 1

Views: 600

Answers (1)

Nathan A
Nathan A

Reputation: 11319

Rather than trying to determine the cause of a closing event to disable certain keystrokes, disable all methods for closing until your "secret" keystroke is entered.

Use a KeyDown event to intercept and record all keystrokes, and have it set a flag if the secret combination is entered, and then call Close().

In your Closing event, always set e.Cancel = true unless that flag is set.

Here's a simple example:

bool _allowClose = false;

void OnKeyDown(object sender, KeyEventArgs e)
{
    if (DetectSecretCombo(e))  //Implement however you see fit.
    {
        _allowClose = true;
        Close();
    }
}

void OnClosing(object sender, ClosingEventArgs e)
{
    _e.Cancel = !_allowClose;
}

Upvotes: 1

Related Questions