OnPaint方法没有正确绘制矩形

l46*_*kok 0 .net c# paint winforms

我有以下绘制矩形的绘制事件(窗体):

void LogicSimulationViewerForm_Paint(object sender, PaintEventArgs e) {
    Rectangle rect = new Rectangle(100, 100, 400, 100);
    Graphics c = rtbLogicCode.CreateGraphics();
    c.DrawRectangle(new Pen(Color.Black, 3), rect);
}
Run Code Online (Sandbox Code Playgroud)

矩形显示片刻,然后立即消失.只有当用户调整表单大小时,矩形才会再次显示.

我该如何解决这个问题?

Dmi*_*ryG 6

不要使用Control.CreateGraphics()方法,使用PaintEventArgs.Graphics属性:

void LogicSimulationViewerForm_Paint(object sender, PaintEventArgs e) {
    Rectangle rect = new Rectangle(100, 100, 400, 100);
    e.Graphics.DrawRectangle(Pens.Black, rect);
}
Run Code Online (Sandbox Code Playgroud)