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