c# 跨线程调用windows窗体控件
在做winform应用的时候,经常碰到使用子线程控制界面上控件信息的问题。
我们用的方法,使用一个计时器来执行一个我们需要的功能,这个计时器在内部开启新的线程运行。
public partial class Form1 : Form
{
System.Threading.Timer time1;
public Form1()
{
InitializeComponent();
time1 = new System.Threading.Timer(Update1, null, 100, 20);
}
private void Update1(object obj)
{
if (pictureBox1.Location.X > 500)
{
pictureBox1.Location = new Point(-100, pictureBox1.Location.Y);
}
pictureBox1.Location = new Point(pictureBox1.Location.X + 3, pictureBox1.Location.Y);
}
}
这时会报异常
这是因为.net 2.0以后加强了安全机制,不允许在winform中直接跨线程访问控件的属性。
这里我们可以增加一句这样的话,继续实现的我们的跨线程访问
在第一个窗口初始化之前运行
Control.CheckForIllegalCrossThreadCalls = false;
public partial class Form1 : Form
{
System.Threading.Timer time1;
public Form1()
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
time1 = new System.Threading.Timer(Update1, null, 100, 20);
}
private void Update1(object obj)
{
if (pictureBox1.Location.X > 500)
{
pictureBox1.Location = new Point(-100, pictureBox1.Location.Y);
}
pictureBox1.Location = new Point(pictureBox1.Location.X + 3, pictureBox1.Location.Y);
}
}
成功运行~