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

时间:2014-04-16 11:46:34

标签: c# multithreading

我想更改光标的位置,但会返回错误。请帮我改变我的代码。我读了关于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);
       }
    }
}

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:-1)

在WPF中它是:

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

B) 打电话给你的" MoveMouse"在GUI线程

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

这是一个有用的链接FOR WINFORMS: http://blog.altair-iv.com/2013/02/ui-access-from-background-thread-in.html

答案 2 :(得分:-2)

对于您的情况,您可以尝试这个

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);
    }
 }
}
相关问题