using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsProgressBar { public partial class Form1 : Form { private void outLog(string str) { txtOut.AppendText(DateTime.Now.ToString() + str + "\n"); } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { btnBegin.Enabled = false; btnStop.Enabled = false; btnFinish.Enabled = false; } private void btnSetup_Click(object sender, EventArgs e) { try { if (txtInput.Text.Trim() != "") { progressBar1.Minimum = 0; progressBar1.Maximum = Convert.ToInt32(txtInput.Text); progressBar1.Step = -1; progressBar1.Value = progressBar1.Maximum; btnSetup.Enabled = false; btnBegin.Enabled = true; outLog("时间设置正确,请按开始键继续。。。"); } } catch { MessageBox.Show("请输入一个正确的秒数!"); } } private void btnBegin_Click(object sender, EventArgs e) { btnBegin.Enabled = false; btnStop.Enabled = true; btnFinish.Enabled = true; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { if (progressBar1.Value > progressBar1.Minimum) { progressBar1.PerformStep(); string per = Convert.ToDouble(progressBar1.Value) / Convert.ToDouble(progressBar1.Maximum) * 100 + "%"; if (per != "0%") { outLog("进度条正在工作,剩余:" + per); } //else //{ // outLog("进度条已完成"); // btnSetup.Enabled = true; //} } else { outLog("进度完成!"); timer1.Stop(); btnBegin.Enabled = false; btnStop.Enabled = false; btnFinish.Enabled = false; btnSetup.Enabled = true; } } private void btnStop_Click(object sender, EventArgs e) { if (timer1.Enabled == true) { outLog("stop"); btnStop.Text = "继续"; timer1.Stop(); } else { outLog("继续工作"); btnStop.Text = "暂停"; timer1.Start(); } } private void btnFinish_Click(object sender, EventArgs e) { outLog("停止工作\n=================="); timer1.Enabled = false; progressBar1.Value = 0; btnSetup.Enabled = true; btnBegin.Enabled = false; btnStop.Enabled = false; btnFinish.Enabled = false; btnStop.Text = "暂停"; } } }
练习笔记:
1、 Convert.ToInt32(txtInput.Text),类型强制转换,字符串型数据转为整型数据。
2、progressBar1.PerformStep(),进度条执行一次步进。 Perform v.执行