Search code examples
c#cursorwait

Can't change the current cursor


The following code tests my Connection. The connection timeout is set to 30 seconds. I wanna Change the current Cursor to the waitcursor but it doesn't work.

My code:

private void pbConnectionTest_Click(object sender,EventArgs e) {
    try {
        Cursor.Current = Cursors.WaitCursor;
        Thread thread = new Thread(new ThreadStart(TestConnection));
        thread.Start();
    } finally {
        Cursor.Current = Cursors.Default;
    }

I also tried to handle the Cursor in my function TestConnection. But it doens't work there ether.

This example works without Problems:

Cursor.Current = Cursors.WaitCursor;
try
{
  Thread.Sleep(5000);  // wait for a while
}
finally
{
  Cursor.Current = Cursors.Default;
}

What am I doing wrong?


Solution

  • This following code is wrong(logically).

    finally 
    {             
        Cursor.Current = Cursors.Default;
    }
    

    Here what happens is

    1. Cursor will be changed to wait cursor.
    2. Thread will be started and, immediately the Cursor will be changed again to default.(before thread is finished).

    So you should place follwing statement after your thread is finished.

            Cursor.Current = Cursors.Default;
    

    Here what you should know is, the call thread.Start(); will immediately return.(does not wait for thread to finish)

    Solution1 Remove statement from finally block and do as follows.

    void TestConnection()
    {
        ..............
        ..................
    
    
       this.Invoke(new MethodInvoker(() =>
       {
            Cursor = Cursors.Default;
       }));   
    }