Home > C#, Tips > [EN] Custom commands CTRL+F4 and ALT+F4

[EN] Custom commands CTRL+F4 and ALT+F4

February 9, 2011 Leave a comment Go to comments

Sometimes there is a need to handle CTRL+F4 and/or ALT+F4 key commands in a custom way. I’ll present how to handle this commands in a Windows forms.

1.  Set Form’s KeyPreview property to true.

2. Override Form’s ProcessCmdKey procedure

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
  if (keyData == (Keys.Control | Keys.F4)) return false;
  return base.ProcessCmdKey(ref msg, keyData);
}

3. Handle Form’s KeyDown event

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.F4)
  {
    if (e.Control) MessageBox.Show("CTRL + F4");
    if (e.Alt) MessageBox.Show("ALT + F4");
    e.Handled = true;
  }
}

4. And the effect is:

Example project: http://cid-e2eed297c7a63060.office.live.com/self.aspx/Publiczny/Samples/CustomF4.zip

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: