Here is a simple solution, albeit not one that is totally easy to fully understand as it does involve catching the WndProc
event and using a few constants from the Windows inderds..:
This is the obvious part:
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Show();
}
Unfortunately we can't use the pictureBox1.LostFocus
event to hide the Picturebox
.
That is because only some controls can actually receive focus when clicking them; a Button
or other interactive controls like a ListBox
, a CheckBox
etc can, too.
But a Panel
, a PictureBox
and also the Form
itself can't receive focus this way. So we need a more global solution.
As ever so often the solution comes form the depths of the Windows message system:
const int WM_PARENTNOTIFY = 0x210;
const int WM_LBUTTONDOWN = 0x201;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN || (m.Msg == WM_PARENTNOTIFY &&
(int)m.WParam == WM_LBUTTONDOWN))
if (!pictureBox1.ClientRectangle.Contains(
pictureBox1.PointToClient(Cursor.Position)))
pictureBox1.Hide();
base.WndProc(ref m);
}
Note that we need to make sure that you can still clcik on the PictureBox
itself; so we check if the mouse is inside its ClientRectangle
..
Simply add this to the form code and every click outside the PictureBox will hide it.