DoubleBuffered设置为true时覆盖OnPaint的问题 [英] A problem with overriding OnPaint when DoubleBuffered set to true

查看:122
本文介绍了DoubleBuffered设置为true时覆盖OnPaint的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个从Panel派生的自定义控件.我用它来显示一个使用BackgroundImage属性的图像.我重写OnClick方法并将isSelected设置为true,然后调用Invalidate方法并在重写的OnPaint中绘制一个矩形. 一切正常,直到我将DoubleBuffered设置为true.绘制矩形,然后将其删除,我不知道为什么会发生这种情况.

I have created a custom control which derives from Panel. I use it to display an Image using BackgroundImage property. I override the OnClick method and set isSelected to true then call Invalidate method and draw a rectangle in overrided OnPaint. Everything goes just fine until I set DoubleBuffered to true. The rectangle is drawn and then it is erased and I can't get why this is happening.

public CustomControl()
    : base()
{
    base.DoubleBuffered = true;

    base.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
}

protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);

    PaintSelection();
}

private void PaintSelection()
{
    if (isSelected)
    {
        Graphics graphics = CreateGraphics();
        graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
    }
}

推荐答案

在您的PaintSelection中,您不应创建新的Graphics对象,因为该对象将绘制到前端缓冲区,然后该缓冲区立即被覆盖后台缓冲区的内容.

In your PaintSelection, you should not create a new Graphics object, because that object will draw to the front buffer, which is then promptly overdrawn by the contents of the back buffer.

PaintEventArgs中传递的Graphics绘画:

protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);
    PaintSelection(pe.Graphics);
}

private void PaintSelection(Graphics graphics)
{
    if (isSelected)
    {
        graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
    }
}

这篇关于DoubleBuffered设置为true时覆盖OnPaint的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆