February 07, 2012   Login   |   Register  
  Search  
  |  
  Home | Blog

The Renegade Blog

Minimize
 Print   

The Renegade Blog

Minimize
 Print   

The Renegade Blog

Minimize
Apr 30

Written by: Renegade
Wednesday, April 30, 2008 12:00 AM

There's always a complicated answer to every problem, but quite often there's a simpler, more elegant solution.

In fixing a bug that involved intercepting ALT + F4, I checked around for different approaches to it and found a few extremely complicated ones that were just nightmarishly long and involved all kinds of low-level keyboard hooks and the Windows API, and voodoo chants and sacrificing chickens and... OK -- They didn't involve any black magic or voodoo, but you get the point. They were messy for what I wanted.

So instead I started poking around and found the “CloseReason” enumeration. Perfect! ALT + F4 is a reason to close a form, and that's what I'm looking for!

There's a little thing there called “UserClosing” in the CloseReason enum and that fit the bill and let me get at that ALT + F4 without any Windows API or any messiness. Here's a code sample that shows how to intercept ALT + F4 and deal with it however you want:

   1:  private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
   2:  {
   3:      if (e.CloseReason == CloseReason.UserClosing)
   4:      {
   5:          e.Cancel = true;
   6:          // Do stuff here!
   7:      }
   8:  }

Tada! Nice and clean and simple and full of goodness! :)

Of course you don't need to cancel the closing there if you don't want to. Just don't handle the FormClosingEventArgs like above (e.Cancel = true).

The .NET framework is just massive, and there's far too much in it for anyone to learn all of it, but a little poking around can really pay off nicely!

Cheers,

Ryan

 

Tags:

Your name:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment    Cancel  
  

The Renegade Blog

Minimize
 Print   

Tweets

Minimize
 Print   
     
Renegade Minds About | Blog | Contact

  Search

Copyright 2010 by Renegade Minds   |   Privacy Statement   |   Terms of Use
Renegade Minds