Search code examples
c#.netwinformstooltip

Create Windows Forms(C#) tooltip that plays animated GIF


I am trying to show GIFs when the user hovers over certain icons on a Windows Forms application. The GIFs must be shown outside the actual area of the form with the perfect solution looking like a tooltip with IsBallon set to True that perfectly wraps around the GIF.

After modifying the solution in a similar question Replacing ToolTip Text with a GIF I was able to render just an image inside of a tooltip. This will not however animate the GIF for whatever reason and my attempts to step through the frames of the GIF have so far failed.


Solution

  • I have done this on a search result form. Hovering over the image would pop-up a larger version of the same image. It was done by creating a form with a Dock.Fill PictureBox during the MouseEnter event of the icon/image. I saved the new PictureBox in the Tag property of the original icon/image. On MouseLeave I just disposed of the form and PictureBox.

    Here's my code, modify to suit your needs:

        void pb_MouseEnter( object sender, EventArgs e )
        {
            // sender was my original image. You may need to perform type checks
            PictureBox pb = ((PictureBox)sender);
            // Ignore empty images
            if (pb.Image == null)
                return;
    
            Form f = new Form();
            f.ControlBox = false;
            f.Enabled = false;
            f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
    
            // Modify to suit your location
            f.Location = new Point( pb.TopLevelControl.Location.X + pb.Location.X - f.Width - 25, MousePosition.Y - f.Height / 2 );
    
            f.ShowInTaskbar = false;
            f.Size = new System.Drawing.Size( 300, 256 );
            f.StartPosition = FormStartPosition.Manual;
            f.TopMost = true;
    
            PictureBox pb2 = new PictureBox();
            pb2.Dock = DockStyle.Fill;
    
            pb2.Image = (Image)pb.Image.Clone();
            pb2.SizeMode = PictureBoxSizeMode.Zoom;
            f.Controls.Add( pb2 );
    
            pb.Tag = pb2;
            f.Show();
            this.Focus();
        }
    
        void pb_MouseLeave( object sender, EventArgs e )
        {
            PictureBox pb = ((PictureBox)sender);
            if (pb.Tag != null)
            {
                PictureBox pb2 = (PictureBox)pb.Tag;
                Form f = (Form)pb2.Parent;
                pb2.Dispose();
                f.Dispose();
                pb.Tag = null;
            }
        }