繁体   English   中英

c#多个线程中的无效操作:跨线程操作无效

[英]c# Invalid operation in several threads:Cross-thread operation not valid

我想更改光标的位置,但返回错误。 请帮助我更改代码。 我读过有关Invoke的文章,但由于我是C#的初学者,所以不知道如何使用。 谢谢!

namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        System.Timers.Timer myTimer = new System.Timers.Timer();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {            
            myTimer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );
            myTimer.Interval = 1000;
            myTimer.Start();              
        }

       public  void DisplayTimeEvent( object source, ElapsedEventArgs e )
       {
            MoveCursor();
       }

       private void MoveCursor()
       {
            this.Cursor = new Cursor(Cursor.Current.Handle);
            Cursor.Position = new Point(Cursor.Position.X - 10, Cursor.Position.Y - 10);
       }
    }
}

这是一个服务器计时器,它从UI线程中触发其计时器事件。 这导致您观察到问题,因为必须与主UI线程上的UI进行交互。

您需要一个UI计时器,它将在主UI线程上触发其计时器事件。 例如: System.Windows.Forms.Timer

在WPF中,它是:

A)将您的计时器更改为:DispatcherTimer-使用此计时器,您可以更改tick事件gui元素

B)在GUI线程中调用“ MoveMouse”

 this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    MoveMouse();
                }));

以下是有关WINFORMS的有用链接: http ://blog.altair-iv.com/2013/02/ui-access-from-background-thread-in.html

对于你的情况,你可以试试这个

namespace WindowsFormsApplication8
{
 public partial class Form1 : Form
 {
    System.Timers.Timer myTimer = new System.Timers.Timer();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {  
        myTimer.Tick += myTimer_Tick;
        myTimer.Interval = 1000;
        myTimer.Start();
    }

    void myTimer_Tick(object sender, EventArgs e)
    {      
        System.Threading.Thread.Sleep(5000); // 5000 is 5 seconds. i.e. after 5 seconds i am changing the cursor position. 
        MoveCursor();
    }

    private void MoveCursor()
    {
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = new Point(Cursor.Position.X - 10, Cursor.Position.Y - 10);
    }
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM