Using multithreaded handle to set the implementation of the busy state of the mouse

  • 2020-05-17 06:12:47
  • OfStack

When we are reading data, or when we are processing a large amount of data, we may need to set the mouse to busy state and wait for the return result. The following code can help with this:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CursorThread
{
    public partial class Form1 : Form
    {
        public delegate int DoSomethingDelegate(int data);
        public Form1()
        {
            InitializeComponent();
        }
        static int DoSomething(int data)
        {
            /// <sumary>
            /// Do something in this method
            /// </sumary>
            Thread.Sleep(300);
            return data++;

        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            DoSomethingDelegate d = DoSomething;
            IAsyncResult ar = d.BeginInvoke(100,null, null);
            while (true)
            {
                this.Cursor = Cursors.WaitCursor;
                if(ar.AsyncWaitHandle.WaitOne(50, false))
                {
                    this.Cursor = Cursors.Arrow;
                    break;
                }
            }
            //Get the result
            int result = d.EndInvoke(ar);
            MessageBox.Show(result.ToString());
        }
    }
}

After clicking the mouse, the mouse will become busy 1 and wait for the DoSomething method call to finish, then return to the arrow state.

You can also do this:


// Set the status of the cursor
this.Cursor = Cursor.Busy;
// Do Something
// Set the status of the cursor
this.Cursor = Cursor.Arrow;

If you cannot use the this keyword when calling a method, you can do this:

private void Method()
{    
         Curosor.Current = Cursor.WaitCursor;
         /// Do Something
         Cursor.Current = Cursor.Arrow;
}


Related articles: