How to hide control when click outside it?

1.7k views Asked by At

I have a WindowForm and some controls on it.

My point is that when I click button "?" on top-right of the datagridview, it will show a picture box and when I click outside the pictureBox, it must invisible.

My MainForm MainForm

MyPictureBox

enter image description here

I have searched some topics on this site, but some dont work, some work partly. Like this.

I also tried:

void pictureBox1_LostFocus(object sender, EventArgs e)
    {
        if (pictureBox1.Visible)
            pictureBox1.Visible = false;
    }

But when I click on button2, button3, ... The pictureBox wasn't invisible.

Any solution will be highly appreciated.

3

There are 3 answers

0
Adam White On

Oh, I have encountered this before...

I was making a Label that you could double click and it would allow you to edit the Label.Text, like a TextBox. However, I was having problems hooking into the events to know when the user had clicked off the Control and wished to stop editing. I tried Control.LostFocus, and Control.Leave, but nothing. I even got frustrated/desperate and tried some silly ones like Control.Invalidated.

What I ended up having to do was subscribe to the Click event of the Form/Container/Control behind it.

However, putting the responsibility of wiring up this event into the Form that wants to use it is poor design. What you can do, however is to make the constructor to Control class require a reference to the owner/parent/container as a parameter. That way, the requirements are not hidden, they must be satisfied before you can get a object instance, and the control can wired up to the Form.Click within itself, where that logic belongs.

    private Form owner;

    public EditLabel(Form Owner)
    {
         this.owner = Owner;
         owner.Click += EndEditing;
    }
0
Kirti On

Add this method in designer.cs:

pictureBoxEvent this.MouseLeave += new EventHandler(pictureBox_MouseLeave);

Add this code in cs file:

private void pictureBox_MouseLeave(object sender, EventArgs e)
{
    pictureBox1.Visible = false;
}
0
Zoltan Rajnai On

I think your pictureBox1 isn't losing focus, cause it never actually GOT focused. Set it to be focused after making it visible.