更新时间:2023-10-21 12:51:52
是
从我拥有的项目中找到了一些旧代码.编辑了一些东西,你应该可以轻松地让它工作.
Found some old code from a project where I had it. Edited out a few things, you should be able to get it working easily.
调用它:
GuiCursor.WaitCursor(() => { yourclass.DoSomething(); });
班级
internal class GuiCursor
{
private static GuiCursor instance = new GuiCursor();
private GuiCursor() { }
static GuiCursor() { }
internal static void WaitCursor(MethodInvoker oper)
{
if (Form.ActiveForm != null && !Thread.CurrentThread.IsBackground)
{
Form myform = Form.ActiveForm;
myform.Cursor = Cursors.WaitCursor;
try
{
oper();
}
finally
{
myform.Cursor = Cursors.Default;
}
}
else
{
oper();
}
}
internal static void ToggleWaitCursor(Form form, bool wait)
{
if (form != null)
{
if (form.InvokeRequired)
{
form.Invoke(new MethodInvoker(() => { form.Cursor = wait? Cursors.WaitCursor : Cursors.Default; }));
}
else
{
form.Cursor = wait ? Cursors.WaitCursor : Cursors.Default;
}
}
}
internal static void Run(Form form)
{
try
{
Application.Run(form);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
根据要求,举个例子.创建一个新的 winform 项目来测试它.默认情况下,您会获得一个 Form1.给它添加一个按钮,双击它,你会得到一个自动生成的方法.
As by request, an example. Create a new winform project to test it out. As default you get a Form1. Add a button to it, double click on it so you get a autogenerated method to it.
用这个替换类 Form1.
Replace the class Form1 with this.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GuiCursor.WaitCursor(() => { DoSomething(); });
}
private void DoSomething()
{
Thread.Sleep(3000);
}
}
internal class GuiCursor
{
private static GuiCursor instance = new GuiCursor();
private GuiCursor() { }
static GuiCursor() { }
internal static void WaitCursor(MethodInvoker oper)
{
if (Form.ActiveForm != null && !Thread.CurrentThread.IsBackground)
{
Form myform = Form.ActiveForm;
myform.Cursor = Cursors.WaitCursor;
try
{
oper();
}
finally
{
myform.Cursor = Cursors.Default;
}
}
else
{
oper();
}
}
internal static void ToggleWaitCursor(Form form, bool wait)
{
if (form != null)
{
if (form.InvokeRequired)
{
form.Invoke(new MethodInvoker(() => { form.Cursor = wait ? Cursors.WaitCursor : Cursors.Default; }));
}
else
{
form.Cursor = wait ? Cursors.WaitCursor : Cursors.Default;
}
}
}
internal static void Run(Form form)
{
try
{
Application.Run(form);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}