WinForm 鼠标忙碌状态

在一个用时比较长的操作里面,如果直接设置 UseWaitCursor = True ,鼠标只能在操作完成后才能响应这个设置。解决办法是新建一个类:

public class HourGlass : IDisposable 
{
    public HourGlass()
    {
        Enabled = true;
    }
    public void Dispose()
    {
        Enabled = false;
    }

    public static bool Enabled
    {
        get { return Application.UseWaitCursor; }
        set
        {
            if (value == Application.UseWaitCursor) return;
            Application.UseWaitCursor = value;
            Form f = Form.ActiveForm;
            if (f != null && f.Handle != null)
                SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1);
        }
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

然后使用:

using (new HourGlass())
{
    // 长时间操作
}