簡體   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