C# 在Windows窗体控件上清除也会清除控件本身-如何防止这种情况?

C# 在Windows窗体控件上清除也会清除控件本身-如何防止这种情况?,c#,.net,graphics,controls,C#,.net,Graphics,Controls,我尝试使用以下方法在Picturebox上绘制自定义选择矩形: void _drag_UpdateView(bool clearOnly, MouseEventArgs e) { System.Diagnostics.Debug.WriteLine("UpdateView"); using (Graphics g = this.i_rendered.CreateGraphics()) { g.Clear(Co

我尝试使用以下方法在Picturebox上绘制自定义选择矩形:

    void _drag_UpdateView(bool clearOnly, MouseEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("UpdateView");
        using (Graphics g = this.i_rendered.CreateGraphics())
        {
            g.Clear(Color.Transparent);
            if (clearOnly)
                return;
            int px = (_drag_start.X > e.Location.X)?e.Location.X:_drag_start.X;
            int py = (_drag_start.Y > e.Location.Y)?e.Location.Y:_drag_start.Y;
            if (px < 0)
                px = 0;
            if (py < 0)
                py = 0;
            int wx = Math.Abs(e.Location.X-_drag_start.X);
            int wy = Math.Abs(e.Location.Y-_drag_start.Y);
            g.DrawRectangle(Pens.LightBlue, px, py, wx, wy);
        }
    }
整个图片盒变黑了。但是,矩形会在其上绘制。 当然,如果我不调用该方法,矩形会自动堆叠。我想删除旧的矩形并创建一个新的矩形,如下所示


有人能描述出哪里出了问题吗?

不要在
OnPaintBackground
OnPaint
以外的任何方法中绘制控件

实际上,出于性能原因,您可能需要它(您不会刷新完整控件,只需动态更改某些内容),但它会使代码变得更加复杂,并且您也始终需要在
Paint
事件中执行相同的工作(因为可能会出于许多其他原因调用它,因此输出应该是相同的)

Paint
中,您甚至不需要使用
CreateGraphics
,图形上下文位于
PaintEventArgs
对象中,因此将代码更改为:

void DoPainting(object sender, PaintEventArgs e)
{
    // Do your calculations
    e.Graphics.DrawRectangle(Pens.LightBlue, px, py, wx, wy);
}

正如@Andersforgren所指出的那样,使用
CreateGraphics
方法并不常见,通常您不需要调用它(例如,在您需要基于图形执行某些计算(如自动调整大小)之前和之后指出的例外情况)。

更改绘制逻辑,在OnPaint/OnPaintBackground中绘制,这样就不需要调用Graphics。清除+1 Adriano,您应该将该注释作为答案。您很少需要使用“CreateGraphics”来绘制控件。@Adriano-现在尝试了,但现在整个控件都变成了白色。-我也看不到矩形。@Tgys如果在Paint事件处理程序中,您不需要使用CreateGraphics,只需使用e.Graphics即可。@Andersforgren我很懒,这是一个简短的答案,没有任何代码或解释,不足以回答!
void DoPainting(object sender, PaintEventArgs e)
{
    // Do your calculations
    e.Graphics.DrawRectangle(Pens.LightBlue, px, py, wx, wy);
}