winforms WinForm应用程序中的沙漏问题

lsmepo6l  于 11个月前  发布在  其他
关注(0)|答案(6)|浏览(141)

在我的WinForm UI程序中,我在启动ThreadPool中的一个方法之前将光标设置为沙漏。
我在UI线程中设置光标的代码看起来像这样:

Application.UseWaitCursor = true;

字符串
当方法完成后,我回到UI线程将光标设置为正常情况。

Application.UseWaitCursor = false;


我的问题是光标停留在沙漏上,直到我不移动鼠标。如果用户等待动作结束而不移动鼠标,这有点令人不安。
有人能帮我吗?
热罗姆

kognpnkq

kognpnkq1#

事实上,还有一种方法可以做到这一点,这是我在研究这个问题几个小时后发现的。
不幸的是,这是一个黑客。
下面是我写的一个方法来处理这个问题。

/// <summary>
    /// Call to toggle between the current cursor and the wait cursor
    /// </summary>
    /// <param name="control">The calling control.</param>
    /// <param name="toggleWaitCursorOn">True for wait cursor, false for default.</param>
    public static void UseWaitCursor(this Control control, bool toggleWaitCursorOn)
    {
        ...

        control.UseWaitCursor = toggleWaitCursorOn;

        // Because of a weird quirk in .NET, just setting UseWaitCursor to false does not work
        // until the cursor's position changes. The following line of code fakes that and 
        // effectively forces the cursor to switch back  from the wait cursor to default.
        if (!toggleWaitCursorOn)
            Cursor.Position = Cursor.Position;
    }

字符串

ltqd579y

ltqd579y2#

还有一种方法:

Cursor.Current = Cursors.WaitCursor;

字符串
完成后,只需将光标变回:

Cursor.Current = Cursors.Default;

atmip9wb

atmip9wb3#

我无法复制这种行为?对我来说很好。
但是,如果使用Control.Cursor = Cursors.WaitCursor方法,需要注意的一点是,它通常是这样使用的:
this.Cursor = Cursors.WaitCursor
这看起来工作正常,但是,this引用表单,所以如果用户将鼠标移动到不同的控件,例如TextBox,那么鼠标不会显示等待光标。
这可能会给用户造成混乱,或者当应用程序忙碌忙于其他工作时,如果用户继续处理其他事情,可能会导致一些问题。

ve7v8dk2

ve7v8dk24#

我的解决办法...

public class SetMouseCursor
{
    public static void Wait()
    {
        Application.UseWaitCursor = true;
        Cursor.Current = Cursors.WaitCursor;
    }

    public static void Default()
    {
        Application.UseWaitCursor = false;
        Cursor.Current = Cursors.Default;
    }
}

字符串

flseospp

flseospp5#

手动设定光标。我就是这么做的。

dsekswqp

dsekswqp6#

一个可重用的解决方案是使用一个小的一次性助手类。

public sealed class WaitCursor : IDisposable
{
    public WaitCursor()
    {
        Application.UseWaitCursor = true;
        Cursor.Current = Cursors.WaitCursor;
    }

    public void Dispose()
    {
        Application.UseWaitCursor = false;
        Cursor.Current = Cursors.Default;
    }
}

字符串
在C#中使用var变得非常简单(示例):

using var waitCursor = new WaitCursor();

using var dbContext = new MyDbContext();
await dbContext.Adresses.LoadAsync();
var adresses = _dbContext.Adressen.Local.ToBindingList();
gridControl1.DataSource = adresses;


默认光标将在当前代码块的末尾自动恢复。不需要显式的try-finally来确保代码安全。

相关问题