Trung Possible Trung Possible - 1 month ago 5
C# Question

(Winform) Cannot click the linklabel after adding it as MouseHover event fired

I have a PictureBox. I want to add automatically a LinkLabel at a specific location when the mouse hover to it. Everything's fine but I can't click on the LinkLabel as it can't stop flickering. This is my code:

private void ptbType1_MouseHover(object sender, EventArgs e)
{
PictureBox ptb = sender as PictureBox;
LinkLabel lkl = new LinkLabel();
lkl.Text = "Change Image...";
lkl.Font = new Font(lkl.Font.FontFamily, 10, FontStyle.Regular);
lkl.BackColor = SystemColors.Window;
lkl.AutoSize = false; lkl.TextAlign = ContentAlignment.MiddleCenter;
lkl.Size = new Size(120, 30); lkl.BorderStyle = BorderStyle.FixedSingle;
lkl.Location = new Point(ptb.Size.Width - 120, 5);
ptb.Controls.Add(lkl);
}


**UPDATE 10/18/2016: The idea using Tooltip to avoid LOTS OF linklabel by gzaxx suggests me to implement another way: A linklabel now has already been on the picture box, its Visible property was set False. When mouse hovers the picturebox, the label appears as Visible -> true, vice versa when mouse leaves. All remain the same: flickering makes it cannot be clicked. The MouseHover Event on the picture box, certainly, is the cause.

Any ideas? thanks for any help!

Answer

Thanks for all your support, I've solved the problem. The key is

  1. When the mouse cursor enter the linklabel, it coincidentally fire the MouseLeave_Event of the picturebox => linklabel disappears

  2. As label vanished, the mouse cursor then enter the picturebox, so MouseHover_Event of the picturebox work => linklabel appears

---> eternal loop -> blinking

I 've dealt with it by this code to check whether the mouse cursor is in linklabel bound area, the linklabel stands still and only disappears when cursor actually get out of the picturebox:

    private void ptbType1_MouseLeave(object sender, EventArgs e)
    {
        PictureBox ptb = sender as PictureBox;
        LinkLabel lkl = ptb.Controls[0] as LinkLabel;
        if (!lkl.Bounds.Contains(ptb.PointToClient(Cursor.Position)))
        {
           lkl.Visible = false;
        }
    }

Done! My 1st question on the site and i myself answer it, brilliant :))