编程语言
首页 > 编程语言> > c# – 如何使用Thread移动PictureBox?

c# – 如何使用Thread移动PictureBox?

作者:互联网

我正在学习C#中的线程,所以我的第一个程序将是2个将要移动的图像.但问题是,当我尝试在线程中执行新点时,我收到错误:

这是我的代码:

namespace TADP___11___EjercicioHilosDatos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int x = 0;
        int y = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread Proceso1 = new Thread(new ThreadStart(Hilo1));
            Proceso1.Start();
        }

        public void Hilo1()
        {   
            while (true) 
            {
                x = pictureBox1.Location.X - 1;
                y = pictureBox1.Location.Y;
                pictureBox1.Location = new Point(x, y);
            }   
        }
    }
}

解决方法:

你必须Invoke它.由于[显而易见]原因,您无法访问由其他线程创建的控件,因此您必须使用委托.几个类似的SO问题:

> How to update the GUI from another thread in C#?(111支票)
> Writing to a textBox using two threads
> How to update textbox on GUI from another thread in C#
> Writing to a TextBox from another thread?

如果你查看第一个链接,Ian的答案很好,将演示如何在.Net 2.0和3.0中执行此操作.或者你可以向下滚动到下一个答案,Marc’s,它将告诉你如何以最简单的方式做到这一点.

码:

//worker thread
Point newPoint = new Point(someX, someY);
this.Invoke((MethodInvoker)delegate {
pictureBox1.Location = newPoint;
// runs on UI thread
});

标签:c,multithreading,picturebox
来源: https://codeday.me/bug/20190718/1494619.html