窗体-异步执行进度

前些天由于匆忙,因此只贴了代码,现在把它补全。

窗体界面如下图:

窗体属性:

  FormBorderStyle:None

  ShowInTaskbar:false

ProgressBar属性:

  Name:progressBar

代码部分:

代码
1 using System;
2 using System.Drawing;
3 using System.Windows.Forms;
4
5 using System.Threading;
6
7 namespace BaseAssembly
8 {
9 public delegate void ChangeValue(int value);
10 public delegate void CloseForm();
11
12 public partial class Form_Loading : Form
13 {
14
15 #region Fields
16
17 private WaitCallback runMethod; //要执行的委托
18 private object state; //作为RunMethod的参数传递
19 private Form callForm; //调用窗体
20
21 #endregion Fields
22
23
24 #region Properties
25
26 /// <summary>
27 /// 异步执行的方法。
28 /// 请在执行的最后使用Invoke调用窗体的Close方法以关闭窗体
29 /// </summary>
30 public WaitCallback RunMethod
31 {
32 get { return this.runMethod; }
33 set { this.runMethod = value; }
34 }
35
36 /// <summary>
37 /// 作为RunMethod的参数传递
38 /// </summary>
39 public object State
40 {
41 get { return this.state; }
42 set { this.state = value; }
43 }
44
45 #endregion Properties
46
47
48 //Constructor
49 public Form_Loading(Form callForm)
50 {
51 this.callForm = callForm;
52 InitializeComponent();
53 }
54
55 /// <summary>
56 /// 进度最大值
57 /// 在异步方法中请使用Invoke调用该方法以更新值
58 /// </summary>
59 /// <param name="value">最大值</param>
60 public void SetProgressBarMaximum(int value)
61 {
62 this.progressBar.Maximum = value;
63 }
64
65 /// <summary>
66 /// 设置进度栏的当前值
67 /// 在异步方法中请使用Invoke调用该方法以更新值
68 /// </summary>
69 /// <param name="value"></param>
70 public void SetProgressBarValue(int value)
71 {
72 if (value > this.progressBar.Maximum)
73 this.progressBar.Value = this.progressBar.Maximum;
74 this.progressBar.Value = value;
75 }
76
77 protected override void OnVisibleChanged(EventArgs e)
78 {
79 //只在显示时执行
80 if (this.Visible && RunMethod != null)
81 {
82 //设置起始位置
83 this.StartPosition = FormStartPosition.Manual;
84 this.Location = new Point(
85 this.callForm.Location.X + (this.callForm.Width - this.Width) / 2,
86 this.callForm.Location.Y + (this.callForm.Height - this.Height) / 2);
87 //执行异步命令
88 //Thread thRunMethod = new Thread(new ParameterizedThreadStart(this.RunMethod));
89 //thRunMethod.Start(this.State);
90 ThreadPool.QueueUserWorkItem(this.RunMethod);
91 base.OnVisibleChanged(e);
92 }
93 }
94
95 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
96 {
97 if (keyData == (Keys)(262144 + 115)) //Alt-F4
98 {
99 return true;
100 }
101 return base.ProcessCmdKey(ref msg, keyData);
102 }
103 }
104 }
posted @ 2010-08-25 20:51  Oo笨蛋  阅读(272)  评论(0编辑  收藏  举报