课程名:Windows应用程序开发入门到精通五:Windows应用程序界面美化
1, 当要进行长时间的计算工作时,不应该在用户界面(UI)主线程中进行从而阻塞主主线程,而应该开一个新的线程来进行。
2, 可以使用ThreadPool.QueueUserWorkItem()来进行异步调用。
3, 从其他线程中更新用户界面中的控件时,需要使用BeginInvoke和delegate来进行。
private
delegate
void
UpdateProgressDelegate(Single PercentDone);
protected
void
UpdateProgress(Single PercentDone)

{
if(InvokeRequired)

{
//marshall the call into the Main UI thread

BeginInvoke(new UpdateProgressDelegate (UpdateProgress),new object []
{PercentDone});//来自外部的调用
return;
}
if (0==PercentDone) isCanceled = true;
btnCancelProgress.Visible =!isCanceled;
pbProgress.Visible=!isCanceled;
pbProgress.Value = (int)PercentDone;
sbpStatus.Text=pbProgress.Value + " % complete";
if(0==PercentDone)
sbpStatus.Text = string.Empty;

}

private
delegate
void
SetStatusTextDelegate(
string
StatusText);

protected
void
SetStatusText(
string
StatusText)

{
if (InvokeRequired)

{
//marshall the call into the main UI thread

BeginInvoke(new SetStatusTextDelegate (SetStatusText),new object[]
{StatusText});//来自外部的调用
return;
}
sbpStatus.Text = StatusText;
}
4, 若有些操作必须是阻塞的,而且很难计算出这些操作的进度,就需要使用等待指针(WaitCursor)。使用try….catch…finally并在finally中将鼠标的指针重新设置为默认状态。 对于时间较长的操作,要给用户提示当前完成的进度。
try

{
this.Cursor = Cursors.WaitCursor;
StatusBar1.Text = "Long process running
";
for(int i=1;i < 50000000;i++)
ProgressBar1.Value = (int)(((float)i / 50000000) * 100);
StatusBar1.Text = "Long process done";
}
finally

{
this.Cursor = Cursors.Default;
}
5, 使用ListBox.Items.AddRange()可以增强性能,比使用Items.Add()方法要提高大约5倍左右。
6, 可以使用IComparer接口来自定义排序的方法。
private
object
[]GetRandomIntArray(
int
n)

{
object[] aintArray = (object[])Array.CreateInstance(typeof(object),n - 1);
Random rnd = new Random();
for(int i = 0;i<aintArray.Length;i++)

{
aintArray[i] = Convert.ToInt32(
rnd.Next(0, System.Int32.MaxValue));
}
return aintArray;
}
object
[]aintArray
=
GetRandomIntArray(Convert.ToInt32(TextBox1.Text));

IComparer Comparer
=
new
DescendingIntComparer();

Array.Sort(aintArray, Comparer);

private
class
DescendingIntComparer :IComparer

{

public int Compare(object x, object y)

{
//Implement our own sorting logic however we want:
return (-1)*Convert.ToInt32(x).CompareTo(Convert.ToInt32(y));
}

}
7, VS安装文件夹下带了一个WizardFramework.dll,可以用于创建标准的”look and feel”向导程序。
8, 自定义绘制状态条:
private
void
sbStatus_DrawItem(
object
sender, System.Windows.Forms.StatusBarDrawItemEventArgs sbdevent)

{
if(sbdevent.Panel.Equals(sbpProgress))

{
Rectangle r = sbdevent.Bounds;
r.Inflate (1,1);
pbProgress.Bounds = r;
}
else if (sbdevent.Panel.Equals(sbpCancelButton))

{
Rectangle r = sbdevent.Bounds;
r.Inflate (1,1);
btnCancelProgress.Bounds = r;
}
}

private
void
frmBaseForm_Load(
object
sender, System.EventArgs e)

{
sbStatus.Controls.Add(btnCancelProgress);
sbStatus.Controls.Add(pbProgress);
}