Can I draw a rectangle with mouseClick? My code is not working so far. Can you help me?
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
Can I draw a rectangle with mouseClick?
If you mean "When the mouse is clicked on my panel I want to display a rectangle" then you can do that like this:
private bool displayRectangle = false;
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
displayRectangle = true;
panel1.Invalidate(false);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (displayRectangle)
{
using (Pen p = new Pen(Color.Black, 2))
{
e.Graphics.DrawRectangle(p, 100, 100, 100, 200);
}
}
}
If you mean "I want to drag the mouse on my panel to create rectangles" then you have a little more work to do.
You need to handle the mouse up, move and down events tracking the delta between the mouse down point and the current position. Finally, on mouse up, you would draw your rectangle. It gets more complicated because you need to use double buffering or an 'xor' rectangle to draw the "drag" rectangle.
These two threads may help:
dragging picturebox inside winform on runtime
Snap to grid mouse locking up