Search code examples
c#winformssystem.drawing

How to hide System.Drawing line with condition


How to hide System.Drawing line with condition:

    System.Drawing.Pen myPen;            
    myPen = new System.Drawing.Pen(System.Drawing.Color.White);           
    System.Drawing.Graphics formGraphics = this.CreateGraphics();

    formGraphics.DrawLine(myPen, 108, 272, 153, 160);  

    myPen.Dispose();
    formGraphics.Dispose();

I want to hide the drawn line formGraphics.DrawLine(myPen, 108, 272, 153, 160); with condition if (x > 1) {} else if (x = 1) {} display it again


Solution

  • Subscribe to the Form.Paint event, either through the designer or in the form constructor. Then in the paint event handler do the conditional drawing. Also make your x variable into a property (public or private) and call Invalidate on the form when it changes. This will cause the form to be redrawing, calling the paint event.

    private int x = 0;
    
    public int X
    {
        get
        {
            return x;
        }
    
        set
        {
            x = value;
            // Cause the form to be redrawn.
            this.Invalidate();
        }
    }
    
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(Color.Black);
    
        // Only draw the line if x == 1.
        if (x == 1)
        {
            e.Graphics.DrawLine(Pens.White, 108, 272, 153, 160);
        }
    }