Shushan
Shushan

Reputation: 393

Can not delete drawing line in c#

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
  isDrawing = true;

  currentPoint = e.Location;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            Graphics bedLine = this.CreateGraphics();
            Pen bedp = new Pen(Color.Blue, 2);
            if (isDrawing)
            {
                bedLine.DrawLine(bedp, currentPoint, e.Location);
                currentPoint = e.Location;
            }
            bedp.Dispose();
        }

dont know how to delete a line, Drawn when mouse moves

Upvotes: 0

Views: 534

Answers (1)

René Vogt
René Vogt

Reputation: 43876

It is a bad idea to draw on your form in any other method than OnPaint. You can not delete a line, it can only be drawn over.

So you should do all your drawing in an overriden OnPaint method. I suggest the following:

public partial class Form1
{
    private bool isDrawing;
    private Point startPoint;
    private Point currentPoint;

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        isDrawing = true;
        startPoint = e.Location; // remember the starting point
    }

    // subscribe this to the MouseUp event of Form1
    private void Form1_MouseUp(object sender, EventArgs e)
    {
        isDrawing = false;
        Invalidate(); // tell Form1 to redraw!
    }
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        currentPoint = e.Location; // save current point
        Invalidate(); // tell Form1 to redraw!
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e); // call base implementation
        if (!isDrawing) return; // no line drawing needed

        // draw line from startPoint to currentPoint
        using (Pen bedp = new Pen(Color.Blue, 2))
            e.Graphics.DrawLine(bedp, startPoint, currentPoint);
    }
}

This is what happens:

  • when the mouse is pressed, we save that position in startPoint and set isDrawing to true
  • when the mouse is moved, we save the new point in currentPoint and call Invalidate to tell Form1 that it should be redrawn
  • when the mouse is released, we reset isDrawing to false and again call Invalidate to redraw Form1 without a line
  • OnPaint draws Form1 (by calling the base implementation) and (if isDrawing is true) a line from startPoint to currentPoint

Instead of overriding OnPaint you can also subscribe to the Paint event of Form1 just as you did with the mouse event handlers

Upvotes: 2

Related Questions