我正在使用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);
}
代码有什么问题。?以下是一些显示确切问题的照片。
第一张照片显示矩形已添加到面板中。当鼠标移动时,它会消失。再次单击面板时,会出现。
答案 0 :(得分:1)
在每次致电Update()
后尝试致电Invalidate()
。
Invalidate
表示应重新绘制控件,但通常需要对Update
进行后续调用以强制进行绘制。
在OnPaint
覆盖中,您应该拨打base.OnPaint(e)
。