我尝试在表单初始化后立即绘制一些框 然而他们并没有出现。 我把代码放在InitializeComponent(); 像这样的
public Form2()
{ InitializeComponent();
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300)); }
但是当我在表单初始化后绘制它们时,它们起作用了!
所以我想我应该等一下,画出盒子
然后我把线程让绘图功能等待10ms
总之,我修改了像这样的代码
public Form2()
{
InitializeComponent();
Thread t1 = new Thread(new ThreadStart(Run));
t1.Start();
}
void Run()
{
Thread.Sleep(10);
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
}
我成功了 所以我的问题是为什么我必须等待一段时间才能在表格初始化后画出一些东西? 并且有没有办法解决这个问题而不使用线程?
答案 0 :(得分:1)
我发现你的问题很有趣并且自己做了一些实验。我设法让它在Form1_Paint回调中工作:)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = e.Graphics; //this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
}
}
编辑:根据Idle_Mind的评论
进行编辑答案 1 :(得分:0)
使用paint事件工作 加上不要使用CreateGraphics而是使用e.Graphics