views:

591

answers:

4

I'm using some controls that trap validation when anything happens--including when users press the exit button. Is there a way to tell if the exit button was pressed?

+8  A: 

If you mean the Close button on the top right of a window, you need to use the FormClosing event.

Ray
I over rode this method to be able to give one of my programs a "minimize to tray" on close before. Pretty simple
phsr
+1  A: 

Assuming that exit button refers to the little 'X' button in the top right corner; no. That is, clicking the button triggers the onClose event directly, without any intermediate button presses or events you can bind to. Once you're in the OnClose, you can try and figure out how you got there, but there's no 'intermediate' step. What I recommend is just have all your validation called from the close event; in case of a validation fail, you can cancel the close via the onClose event args, and work from there.

GWLlosa
That explains what I was seeing when I tried to trap the ActiveControl object. Thanks you're right on.
Jeff
A: 

Thanks all. Found a solution that avoided this altogether.

I was attempting to use Infragistics LimitToList feature of a drop down. However, that feature prevents ALL other events from firing--including form closing! As a work around I was thinking of checking for the exit button being pressed inside the LimitToList feature and then disabling LimitToList in order to allow the exit to take place. So I started checking ActiveControl, yada, yada, but ran into tons of problems (what happens if another form is opened up, etc)

So I scrapped the LimitToList feature and wrote my own validating event using the standard validating method. Why anyone write a feature that pre-empts form closing is beyond me!

Jeff
+4  A: 

To add to what Ray said, you could check the form's FormClosing event.

Specifically, look at the FormClosingEventArgs's CloseReason property. If the user clicked the 'x' on the top right corner of the form, the value of this property will be UserClosing.

However, if you have your own Close button that closes the form, this property will have the same value so you can't tell how the user closed the form.

What I do is add a bool field to my form called something like _closeButtonClicked, and set this to true if my Close button was clicked. In my FormClosing event I check for e.CloseReason == UserClosing and _closeButtonClicked.

This works for me but I'd like to know if there's a better way.

Jay Riggs