Click to See Complete Forum and Search --> : How to catch Alt+F4?


Andi
January 3rd, 2005, 09:56 AM
....next question....

hi all,

-- in my MainForm method i am creating a dialog.
-- if the user clicks OK (in this dialog), everything´s fine...the application goes on
-- if the user clicks the Cancel button ==> i call Application.Exit() and anything will be closed - fine!
-- but if the user presses Alt+F4, the dialog closes but the application will start....

==> what i want:
if the user clicks Alt+F4, the same must happen as clicking the Cancel button

>>>>
so
a) how to catch an key event (must i add a key handler to the dialog form if yes, HOW)?
b) how can i catch the X (the icon in the very right edge up) event?


thanx a lot,
andi

ctwoodward
January 3rd, 2005, 10:05 AM
WEll to catch the X in the corner you have to override the OnClosing Event

Here's some that I use:


protected override void OnClosing(CancelEventArgs e)
{
log.Debug(String.Format("Onclosing called, this.sessionEnding = {0}",this.sessionEnding));
if (this.sessionEnding)
{
//Windows IS shutting down
e.Cancel = false;
this.ShutDown();
}
else //windows isn't closing
{
//Method overridden so we can minimize the app instead of closing it
e.Cancel = true;
//let's minimize the form, and hide it
this.WindowState = FormWindowState.Minimized;
Hide();
}
}


Basically, as long as the compute risn't shutting down (sessionEnding) it just hides the form.

And for Alt-F4 you will have to write a OnKeyDown Event handler and attachit to whatever might had focus when the user presses alt-f4

private void ConversationDisplayBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs kea)
{
if (kea.Alt & (kea.Code == *whatever F4 equals*))
{

}
}

Andi
January 3rd, 2005, 11:32 AM
hi,

thank your for your answer!
it works fine.

meanwhile i found an answer for my other key event question:

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnKeyPressEvent);
...
...
...
...
...
private void OnKeyPressEvent(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//.........
}


thanx a lot,
andi