C#Panel.Refresh()未调用paint方法



我正在尝试调用panel1绘制方法,用橙色线重新绘制面板(它是用蓝色线启动的)。

我尝试过invalidate()、update()和refresh(),但似乎没有什么能调用panel1…的paint事件

油漆事件处理程序已添加到面板1:

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

有人能帮忙吗?

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();
    }
}

Application.Run(testForm);会阻塞,直到表单关闭,所以当调用drawNewLine()时,表单就不存在了(创建一个按钮,点击并检查自己,代码就可以工作了)。Invalidate()应该可以正常工作。

此外,您不应该在paint事件中处理传递给代码的Graphics对象。你不负责创建它,所以让创建它的代码来销毁它

此外,由于正在创建Pen对象,请先对其进行处置。

最新更新