Question

I am trying to call panel1 paint method to repaint the panel with a orange line (it is initiated with a blue line).

I have tried invalidate(), update() and refresh(), but nothing seems to call the paint event of panel1...

The paint event handler have been added to the panel1:

this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);

Can someone please assist?

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 testForm = new Form1();
        Application.Run(testForm);

        testForm.drawNewLine();
    }
}

public partial class Form1 : Form
{
    bool blueLine = true;
    bool orangeLine = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        if (blueLine == true)
        {
            Pen bluePen = new Pen(Color.Blue, 3);
            g.DrawLine(bluePen, 30, 50, 30, 250);
        }
        else if (orangeLine == true)
        {
            Pen orangePen = new Pen(Color.Orange, 3);
            g.DrawLine(orangePen, 30, 50, 30, 250);
        }

        g.Dispose();
    }

    public void drawNewLine()
    {
        blueLine = false;
        orangeLine = true;
        //panel1.Invalidate();
        //panel1.Update();
        panel1.Refresh();
    }
}
Was it helpful?

Solution

Application.Run(testForm); blocks until form is closed, so when drawNewLine() is called - form does not exist anymore (create a button which calls it on click and check yourself, the code is working). Invalidate() should work just fine.

Also, you should not dispose Graphics object which is passed to your code in paint event. You were not responsible for creating it, so let the code which created it to destroy it.

Also, dispose Pen objects since you are creating them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top