Reputation: 1417
I am drawing a rectangle using CreateGraphics
with MouseDrag
and on MouseUp
, I add a RectangleShape
(Microsoft.VisualBasic.PowerPacks
). But the shape is not visible. Actually shape is added to ShapeContainer
, but not shown. AND when I click on Panel
, it shows up.
Below is my code to do so.
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);
}
What is wrong with the code.? Following are some photos that shows the exact problem.
First photo shows that the rectangle is added to panel. When mouse moved, it disappears. Again when you click on the panel, is appears.
Upvotes: 0
Views: 719
Reputation: 6026
Try calling Update()
after each of your calls to Invalidate()
.
Invalidate
indicates that the control should be repainted but you typically need the subsequent call to Update
to force that painting to occur.
In your OnPaint
override you should be calling base.OnPaint(e)
.
Upvotes: 1