如果我在处理任务之前打开 WaitCursor 然后将其恢复为默认值,我通常会得到这种代码模式:
try {
Cursor.Current = Cursors.WaitCursor;
MyProcessingTask();
}
catch (Exception ex) {
Cursor.Current = Cursors.Default;
MessageBox.Show(ex.ToString());
}
finally { Cursor.Current = Cursors.Default; }
我需要在 catch block 中包含 Cursor.Current = Cursors.Default; 以便为 MessageBox 提供默认光标使用。
有没有更好的方法来编写这段代码而不必编写两个 Cursor.Current = Cursors.Default; 语句?
请您参考如下方法:
您可以创建一个一次性类并利用 using 语法糖,即:
class WaitingCursor : IDisposable
{
public WaitingCursor()
{
Cursor.Current = Cursors.WaitCursor;
}
public void Dispose()
{
Cursor.Current = Cursors.Default;
}
}
用法:
try
{
using (var wcurs = new WaitingCursor())
{
MyProcessingTask();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
