如何让我的面板停止闪烁

How to make my panel stop flickering

你好,我正在尝试制作一个面板,当它悬停在图片上时会显示一些文本,我希望它跟随光标,所以我

System.Windows.Forms.Panel pan = new System.Windows.Forms.Panel();
    public Form1()
    {
        InitializeComponent();
        Product p = new Product();
        p.SetValues();
        this.pictureBox1.Image = (Image)Properties.Resources.ResourceManager.GetObject("pictureName");

    }

    private void pictureBox1_MouseEnter(object sender, EventArgs e)
    {
        pan.Height = 200;
        pan.Width = 100;
        pan.BackColor = Color.Blue;
        this.Controls.Add(pan);
        pan.BringToFront();
        //pan.Location = PointToClient(Cursor.Position);
    }

    private void pictureBox1_MouseLeave(object sender, EventArgs e)
    {
        Controls.Remove(pan);
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        pan.Location = PointToClient(Cursor.Position);  
    }

我尝试添加 this.doublebuffered = true; 但是当我移动鼠标时它看起来像是面板的残像

当我将鼠标悬停在我的图片上时,它会显示面板,但它会疯狂闪烁 这是正常现象还是有解决办法或者这是我的电脑问题

this.DoubleDuffered = true; 添加到 Form 只会影响 Form,不会影响 Panel

所以使用双缓冲 Panel subclass:

class DrawPanel : Panel
{
    public DrawPanel ()
    {
      this.DoubleBuffered = true;
    }
}

然而,四处移动大件物品会造成伤害。 顺便说一句,PictureBox class 已经是双缓冲的。此外,将面板添加到 PictureBox 似乎更合乎逻辑,而不是表单:pictureBox1.Controls.Add(pan); 并将 pictureBox1.Refresh(); 添加到 MouseMove.

Update:因为你不在Panel上画画,还需要它与PictureBox重叠,所以上面的想法并不适用;使用 subclass 不是必需的,尽管它在某些时候可能会派上用场。是的,需要将面板添加到窗体的控件集合中!

这段代码在这里工作得很好:

public Form1()
{
    InitializeComponent();

    // your other init code here

    Controls.Add(pan);  // add only once
    pan.BringToFront();
    pan.Hide();         // and hide or show
    this.DoubleDuffered = true  // !!
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    pan.Hide();         // hide or show
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    pan.Location = pictureBox1.PointToClient(Cursor.Position);
    pictureBox1.Refresh();  // !!
    Refresh();              // !!
}

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    pan.Height = 200;
    pan.Width = 100;
    pan.BackColor = Color.Blue;
    pan.Location = pictureBox1.PointToClient(Cursor.Position);
    pan.Show();        // and hide or show
}

看起来你错过了 doublebuffering Formrefreshing 的正确组合, FormPictureBox.