views:

108

answers:

2

I would like to close a modal form when the user clicks outside (anywhere on the computer desktop) the modal form. How can we do this as a modal form is not meant to lose focus.

A: 

I don't think you need to make it modal... then you can take siride's option of closing it on the Deactivate event.

The reason you don't need to make it modal: The first time you display it, it will have the focus and be topmost. Modal prevents you from clicking somewhere else, but you want to be able to click somewhere else... and when you do, the form goes away, so there are no modal needs.

James B
What if the programmer cannot change the modal nature? Suppose it's by design? Still, if required, there are other ways. I won't down vote you, though I feel you didn't understand the possibilities.
Nayan
Besides, Guamez said, user can click "Desktop". Even then the code should work. You can always click desktop even if your forms are modal.. except some special scenarios.
Nayan
Going with the assumption that if he's in the code enough to respond to user clicks, he can probably decide how the form itself is displayed. What other ideas are you thinking?
James B
Right, the user CAN click the desktop... which will still trigger the LostFocus event, so it should still work. It will also work if the user clicks in another window, or in the main window of the same app... which is my understanding of what the OP is looking for.
James B
Have you actually tried LostFocus event, James? I don't think so. :) It doesn't work the way you are expecting... unless you prove me wrong with some "working" code!
Nayan
(1) it's actually the deactivate event, because it's a form, and (2) this is how it works for a non-modal form, which is my point... don't use a modal form, and it will behave how the OP wants
James B
But it doesn't work for modal forms. For is modal - that is the point OP has mentioned.
Nayan
A: 

You need to hook mouse (and keyboard if required) and capture their events. Then check if the click happened outside the form (and area). If yes, flag a sign which can be read by the model form that it can close down.

Algo:

  1. Hook mouse click event.

  2. When callback function is called, check for the click position - if it's inside your form or not (you might need to translate the locations to Desktop locations - I hope you know how to!)

  3. If the point is outside the form, set a flag (boolean or anything that makes you happy). Make sure the form can read the flag somehow.

  4. Trigger an event for form to capture. In it's handler read the flag status. If true, close/unload the form.

This page will tell you technical details and functions.

Nayan
That's a lot of work for what could be a simple answer. If the OP absolutely needs it to be a modal form (and I can't think why he would), then what you're saying will work (it's still a lot of effort). I prefer simple solutions, however, whenever possible
James B
Let OP decide that :)
Nayan