加载进度条问题的探讨
我现在做一个登录窗体,点击登录按钮后执行下面动作:
1、更新本地数据库。
2、打开主窗体,并关掉登录窗体。
因为执行时间有点长,我想加入一个进度条。
小弟对多线程编程一知半解,在BackgroudWorker的DoWork事件里,如何计算动作执行完成的百分比呢?如何得到窗体的Show方法所用的时间呢?
虚心向各位高手请教,谢谢!
------解决方案--------------------按照楼主的情况,基本可以不永多线程,加个ProgressBar,设置Style=Marquee;假的进度条好啦
------解决方案--------------------//你测试一下下面这个代码。
public interface ISplashForm
{
void SetStatusInfo(string NewStatusInfo);
}
public class Splasher
{
private static Form m_SplashForm = null;
private static ISplashForm m_SplashInterface = null;
private static Thread m_SplashThread = null;
private static string m_TempStatus = string.Empty;
/// <summary>
/// 显示过渡窗口
/// </summary>
public static void Show(Type splashFormType)
{
if (m_SplashThread != null)
return;
if (splashFormType == null)
{
throw (new Exception( "splashFormType is null "));
}
m_SplashThread = new Thread(new ThreadStart(delegate()
{
CreateInstance(splashFormType);
Application.Run(m_SplashForm);
}));
m_SplashThread.IsBackground = true;
m_SplashThread.SetApartmentState(ApartmentState.STA);
m_SplashThread.Start();
}
/// <summary>
/// 设置载入状态
/// </summary>
public static string Status
{
set
{
if (m_SplashInterface == null || m_SplashForm == null)
{
m_TempStatus = value;
return;
}
m_SplashForm.Invoke(
new SplashStatusChangedHandle(delegate(string str) { m_SplashInterface.SetStatusInfo(str); }),
new object[] { value }
);
}
}
/// <summary>
/// 关闭过渡窗口
/// </summary>
public static void Close()
{
if (m_SplashThread == null || m_SplashForm == null) return;
try
{
m_SplashForm.Invoke(new MethodInvoker(m_SplashForm.Close));
}
catch (Exception)
{
}
m_SplashThread = null;
m_SplashForm = null;
}
private static void CreateInstance(Type FormType)
{
object obj = FormType.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
m_SplashForm = obj as Form;
m_SplashInterface = obj as ISplashForm;
if (m_SplashForm == null || m_SplashInterface == null)
{
throw (new Exception());
}
if (!string.IsNullOrEmpty(m_TempStatus))
m_SplashInterface.SetStatusInfo(m_TempStatus);
}
private delegate void SplashStatusChangedHandle(string NewStatusInfo);
}
调用实例:
加一窗口:public class Form1 :Form,ISplashForm{