[英]Shapes doesn't show on panel in winform
我正在使用CreateGraphics
和MouseDrag
绘制一个矩形,并且在MouseUp
添加了RectangleShape
( Microsoft.VisualBasic.PowerPacks
)。 但是形状不可见。 实际上,形状已添加到ShapeContainer
,但未显示。 并且,当我单击Panel
,它会显示出来。
下面是我的代码。
Rectangle rect;
Point p;
Size s;
bool mouseDown;
private ShapeContainer shapeContainer1 = new ShapeContainer();
public Form1 ()
{
InitializeComponent();
// This will reduce flicker (Recommended)
this.DoubleBuffered = true;
this.shapeContainer1.Parent = this.panel1;
this.shapeContainer1.Enabled = false;
}
private void panel1_MouseDown (object sender, MouseEventArgs e)
{
this.panel1.SendToBack();
s.Height = 0;
s.Width = 0;
p = this.panel1.PointToClient(System.Windows.Forms.Cursor.Position);
rect = new Rectangle(p, s);
this.panel1.Invalidate();
mouseDown = true;
}
private void panel1_MouseMove (object sender, MouseEventArgs e)
{
if (mouseDown)
{
this.panel1.SendToBack();
p = this.panel1.PointToClient(System.Windows.Forms.Cursor.Position);
rect = new Rectangle(rect.Left, rect.Top, p.X - rect.Left, p.Y - rect.Top);
this.panel1.Invalidate();
}
}
protected override void OnPaint (PaintEventArgs e)
{
Graphics g = this.panel1.CreateGraphics();
if (mouseDown)
{
using (Pen pen = new Pen(Color.Red, 2))
{
this.panel1.SendToBack();
g.DrawRectangle(pen, rect);
}
}
}
private void panel1_MouseUp (object sender, MouseEventArgs e)
{
this.panel1.SendToBack();
shapeContainer1.Size = this.panel1.Size;
shapeContainer1.Location = this.panel1.Location;
RectangleShape rectangle = new RectangleShape();
rectangle.Location = rect.Location;
rectangle.Size = rect.Size;
rectangle.Name = "rectShape";
rectangle.Parent = this.shapeContainer1;
rectangle.Visible = true;
this.shapeContainer1.Shapes.Add(rectangle);
}
代码有什么问题?? 以下是显示确切问题的一些照片。
第一张照片显示该矩形已添加到面板中。 当鼠标移动时,它消失了。 当您单击面板上时,再次出现。
每次调用Invalidate()
之后,尝试调用Update()
Invalidate()
。
Invalidate
表示应重新绘制控件,但通常需要随后对Update
调用来强制进行绘制。
在OnPaint
覆盖中,您应该调用base.OnPaint(e)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.