Winform 动态等待执行完成 Loading

public static class OtherExtend
{
    /// <summary>
    /// 图示等待执行完成
    /// </summary>
    /// <param name="userControl">父窗体</param>
    /// <param name="action">执行动作</param>
    /// <param name="msg">等待信息</param>
    /// <param name="finalAction">结束时动作</param>
    public static void ShowLoading(this UserControl userControl, Action action, string msg = "Waiting......", Action finalAction = null)
    {
        GlobalCommFunc.LongThread(() =>
        {
            ShowLoading(userControl.FindForm(), action, msg, finalAction);
        });            
    }
    /// <summary>
    /// 图示等待执行完成
    /// </summary>
    /// <param name="form">父窗体</param>
    /// <param name="action">执行动作</param>
    /// <param name="msg">等待信息</param>
    /// <param name="finalAction">结束时动作</param>
    public static void ShowLoading(this Form form, Action action, string msg = "Waiting......", Action finalAction = null)
    {
        string rslt = null;
        try
        {
            CreateWaitDialog(form, msg);
            action.Invoke();
        }
        catch (Exception ex)
        {
            rslt = ex.Message;
        }
        finally
        {
            CloseWaitDialog();
            if (finalAction != null)
            {
                finalAction.Invoke();
            }
            if (!string.IsNullOrEmpty(rslt))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(rslt);
            }
        }
    }
    static void CreateWaitDialog(Form parent, string description)
    {
        if (SplashScreenManager.Default == null)
        {
            SplashScreenManager.ShowForm(parent, typeof(FrmWait), false, true, false);
        }
        lock (_objFormVisible)
        {
            if (SplashScreenManager.Default != null)
            {
                SplashScreenManager.Default.SetWaitFormCaption("Please Wait");
                SplashScreenManager.Default.SetWaitFormDescription(description);
            }
        }            
    }
    /// <summary>
    /// 关闭等待窗口
    /// </summary>
    static void CloseWaitDialog()
    {
        if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
        {
            lock (_objFormVisible)
            {
                if (SplashScreenManager.Default.IsSplashFormVisible)
                {
                    SplashScreenManager.CloseForm();
                }                    
            }
        }
    }
    private static readonly object _objFormVisible = new object();

}
posted @ 2024-03-19 14:21  wesson2019  阅读(19)  评论(0编辑  收藏  举报