C# Panel.Refresh() 不调用 Paint 方法
题
我正在尝试打电话 面板1 Paint 方法用橙色线重新绘制面板(以蓝色线启动)。
我尝试过invalidate()、update()和refresh(),但似乎没有任何东西调用panel1的paint事件...
绘制事件处理程序已添加到 panel1 中:
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()
应该可以正常工作。
另外,您不应该丢弃 Graphics
在绘制事件中传递给您的代码的对象。你不负责创建它,所以让创建它的代码来销毁它。
另外,处置 Pen
对象,因为您正在创建它们。
不隶属于 StackOverflow