protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics dc = e.Graphics ;
int i;
i = 2;
while (true)
{
if (2 == i)
{
Pen whitePen = new Pen(Color.White, 2);
dc.DrawEllipse(whitePen, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 1;
}
else
{
Pen redPan = new Pen(Color.Red, 2);
dc.DrawEllipse(redPan, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 2;
}
}
这段代码有什么问题?
{
base.OnPaint(e);
Graphics dc = e.Graphics ;
int i;
i = 2;
while (true)
{
if (2 == i)
{
Pen whitePen = new Pen(Color.White, 2);
dc.DrawEllipse(whitePen, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 1;
}
else
{
Pen redPan = new Pen(Color.Red, 2);
dc.DrawEllipse(redPan, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 2;
}
}
这段代码有什么问题?
在OnPaint中DoEvents,如果此时被遮挡或是引发重绘,软件就会死掉了。很容易死循环的做法。
{
base.OnPaint(e);
Graphics dc = e.Graphics ;
int i;
i = 2;
while (true)
{
if (2 == i)
{
Pen whitePen = new Pen(Color.White, 2);
dc.DrawEllipse(whitePen, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 1;
}
else
{
Pen redPan = new Pen(Color.Red, 2);
dc.DrawEllipse(redPan, 0, 50, 50, 50);
DateTime start = DateTime.Now;
//最多循环10秒
while ((DateTime.Now - start).Seconds < 2)
{
Application.DoEvents();
}
i = 2;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread thr = new Thread(new ThreadStart(Run));
thr.IsBackground = true;
thr.Start();
} private void Run()
{
int i = 0;
while (true)
{
Graphics g = this.CreateGraphics();
Pen whitePen = new Pen(Color.White, 2);
Pen redPan = new Pen(Color.Red, 2);
if (i % 2 == 0)
{
g.DrawEllipse(whitePen, 0, 50, 50, 50);
}
else
{
g.DrawEllipse(redPan, 0, 50, 50, 50);
}
g.Dispose();
i++;
Thread.Sleep(1000);
}
}
如楼上所说。执行pen对象的Dispose方法.因为OnPaint是在窗体收到WM_PAINT的时候调用的,而你的Application.DoEvents会执行消息循环,此时如果遮住屏幕又会触发OnPaint,你实际会嵌套很多次,尽量不要这么做,把这些内容放在一个定时器中实现。
我写了释放语句。但是在程序停止的时候还是出错System.Runtime.InteropServices.ExternalException