1. 使用 WinForms:
using System;
using System.Threading;
using System.Windows.Forms;
public class MainForm : Form
{
private ProgressBar progressBar;
private Button startButton;
public MainForm()
{
InitializeComponents();
}
private void InitializeComponents()
{
progressBar = new ProgressBar
{
Minimum = 0,
Maximum = 100,
Dock = DockStyle.Top
};
startButton = new Button
{
Text = "Start",
Dock = DockStyle.Bottom
};
startButton.Click += StartButton_Click;
Controls.Add(progressBar);
Controls.Add(startButton);
}
private void StartButton_Click(object sender, EventArgs e)
{
// 模拟一个任务,更新进度条
for (int i = 0; i <= 100; i++)
{
progressBar.Value = i;
Thread.Sleep(50); // 模拟耗时操作
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
2. 使用 WPF:
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
public partial class MainWindow : Window
{
private ProgressBar progressBar;
private Button startButton;
public MainWindow()
{
InitializeComponents();
}
private void InitializeComponents()
{
progressBar = new ProgressBar
{
Minimum = 0,
Maximum = 100,
VerticalAlignment = VerticalAlignment.Top
};
startButton = new Button
{
Content = "Start",
VerticalAlignment = VerticalAlignment.Bottom
};
startButton.Click += StartButton_Click;
Content = new Grid
{
Children =
{
progressBar,
startButton
}
};
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
// 模拟一个任务,通过Dispatcher更新进度条
new Thread(() =>
{
for (int i = 0; i <= 100; i++)
{
Dispatcher.Invoke(() => progressBar.Value = i);
Thread.Sleep(50); // 模拟耗时操作
}
}).Start();
}
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new MainWindow());
}
}
这两个示例分别演示了在WinForms和WPF中创建带有进度条的简单界面。注意,上述示例中的任务仅是模拟的,实际中可能需要根据实际业务需求修改。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6377/C#