Code Vader
Code Vader

Reputation: 755

Closing a form that was opened by ShowDialog()

I have a winform application where I've written my own little color picker that will only display system colours. It's basically a TableLayoutPanel with a bunch of smaller panels added to it, to which I just set the background color.

Pretty simple:

enter image description here

Now I'm opening this form for with:

using (frmColourWindow colourPicker = new frmColourWindow (Cursor.Position.X, Cursor.Position.Y, findingPriority))
{
    colourPicker.ShowDialog();
    if (!colourPicker.SelectedColor.IsEmpty)
    {
        pnlColor.BackColor = colourPicker._SelectedColor;
    }                    
}

and closing it with by setting the DialogResult when the user has clicked on one of the color panels.

This all works pretty good, the only thing I can not manage to get right is by closing the form when it loses focus (E.g. when the user clicks somewhere else or starts typing). I've had a look at the Deactivate, LostFocus, and Leave events. Just can't seem to get those events to fire when I want them to. Maybe I'm missing something obvious?

Upvotes: 4

Views: 7677

Answers (2)

Bojan B
Bojan B

Reputation: 2111

As I mentioned in the comments, when using the ShowDialog() you can only use the Dialog you have opened and thus it never looses focus, so event like Deactivate, LostFocus and Leave won't work.

You need to use the Show() command to use those event to close the opened Form.

As to addressing the issue you pointed out in the comments about assigning the color to the object. you can do the following:

Declare a public Property

Color SelectedColor {get; private set; }

In your color picker and change your using statement to this:

var colourPicker = new frmColourWindow (Cursor.Position.X, Cursor.Position.Y, findingPriority);
colourPicker.Closed += (o, args) => { pnlColor.BackColor = colourPicker.SelectedColor };
colourPicker.Show(); 

This is of course just one of many possible solutions for that.

Upvotes: 3

Owen Pauling
Owen Pauling

Reputation: 11871

You can achieve this by displaying the form with the Show() method and then using the Form.Deactivate event.

Upvotes: 0

Related Questions