我如何向用户显示等待/忙碌游标(通常是沙漏),让他们知道程序正在做什么?
当前回答
在前面的基础上,我的首选方法(因为这是一个经常执行的操作)是将等待游标代码包装在一个IDisposable助手类中,这样它就可以与using()(一行代码)一起使用,接受可选参数,在其中运行代码,然后清理(恢复游标)。
public class CursorWait : IDisposable
{
public CursorWait(bool appStarting = false, bool applicationCursor = false)
{
// Wait
Cursor.Current = appStarting ? Cursors.AppStarting : Cursors.WaitCursor;
if (applicationCursor) Application.UseWaitCursor = true;
}
public void Dispose()
{
// Reset
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
用法:
using (new CursorWait())
{
// Perform some code that shows cursor
}
其他回答
好的,其他人的观点很清楚,但我想补充一些,如下:
Cursor tempCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
//do Time-consuming Operations
Cursor.Current = tempCursor;
在窗体或窗口级别使用UseWaitCursor更容易。 一个典型的用例如下所示:
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Enabled = false;//optional, better target a panel or specific controls
this.UseWaitCursor = true;//from the Form/Window instance
Application.DoEvents();//messages pumped to update controls
//execute a lengthy blocking operation here,
//bla bla ....
}
finally
{
this.Enabled = true;//optional
this.UseWaitCursor = false;
}
}
为了获得更好的UI体验,你应该在不同的线程中使用异步。
对于Windows窗体应用程序,可选的禁用ui控件是非常有用的。所以我的建议是这样的:
public class AppWaitCursor : IDisposable
{
private readonly Control _eventControl;
public AppWaitCursor(object eventSender = null)
{
_eventControl = eventSender as Control;
if (_eventControl != null)
_eventControl.Enabled = false;
Application.UseWaitCursor = true;
Application.DoEvents();
}
public void Dispose()
{
if (_eventControl != null)
_eventControl.Enabled = true;
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
用法:
private void UiControl_Click(object sender, EventArgs e)
{
using (new AppWaitCursor(sender))
{
LongRunningCall();
}
}
你可以使用Cursor.Current。
// Set cursor as hourglass
Cursor.Current = Cursors.WaitCursor;
// Execute your time-intensive hashing code here...
// Set cursor as default arrow
Cursor.Current = Cursors.Default;
但是,如果散列操作非常长(MSDN将其定义为超过2-7秒),则可能应该使用游标以外的可视反馈指示器来通知用户进度。有关更深入的指导方针,请参阅本文。
编辑: 正如@Am指出的那样,您可能需要调用Application.DoEvents();在游标。Current = Cursors.WaitCursor;以确保沙漏是真实显示的。
使用下面的类,您可以使Donut的建议“异常安全”。
using (new CursorHandler())
{
// Execute your time-intensive hashing code here...
}
类CursorHandler
public class CursorHandler
: IDisposable
{
public CursorHandler(Cursor cursor = null)
{
_saved = Cursor.Current;
Cursor.Current = cursor ?? Cursors.WaitCursor;
}
public void Dispose()
{
if (_saved != null)
{
Cursor.Current = _saved;
_saved = null;
}
}
private Cursor _saved;
}
推荐文章
- 如何强制LINQ Sum()返回0而源集合是空的
- 将值附加到查询字符串
- Selenium c# WebDriver:等待元素出现
- 我如何添加双引号的字符串,是在一个变量?
- 如何检查一个视图在Android中是否可见?
- 如何创建数组。包含不区分大小写的字符串数组?
- 检查字符串是否包含字符串列表中的元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API