简体   繁体   中英

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

I want to change position of my coursor but it returns error. Please help me change my code. I read about Invoke but I don't know how to use as I am a beginner to c#. Thank you!

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);
       }
    }
}

This is a server timer which fires its timer events away from the UI thread. Which causes the problem you observe because you must interact with UI on the main UI thread.

You need a UI timer which will fire its timer events on the main UI thread. For instance: System.Windows.Forms.Timer .

In WPF it is :

A) change your timer to : DispatcherTimer - with this Timer you can change in the tick event gui elements

B) Call your "MoveMouse" in the GUI Thread

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

Heres a useful link FOR WINFORMS: http://blog.altair-iv.com/2013/02/ui-access-from-background-thread-in.html

for your case you may try this

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);
    }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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