| 功能 | WinForms (System.Windows.Forms) | WPF (System.Windows / Microsoft.Win32) |
|---|---|---|
| MessageBox | System.Windows.Forms.MessageBox | System.Windows.MessageBox |
| OpenFileDialog | System.Windows.Forms.OpenFileDialog | Microsoft.Win32.OpenFileDialog |
| SaveFileDialog | System.Windows.Forms.SaveFileDialog | Microsoft.Win32.SaveFileDialog |
private void WFMessageBoxClicked(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show(
"Hello from Windows Forms!",
"Hello World!",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void WPFMessageBoxClicked(object sender, RoutedEventArgs e)
{
System.Windows.MessageBox.Show(
"Hello from WPF!",
"Hello World!",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
關鍵差異: WPF 版本使用 RoutedEventArgs、MessageBoxButton、MessageBoxImage 列舉,支援更豐富的 UI 整合。
private void WinFormsDialogClicked(object sender, EventArgs e)
{
using (var dialog = new System.Windows.Forms.OpenFileDialog())
{
dialog.Title = "選擇檔案";
dialog.Filter = "文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*";
dialog.Multiselect = true;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (var file in dialog.FileNames)
{
// 處理選取的檔案
}
}
}
}
private void WPFDialogClicked(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
Title = "選擇檔案",
Filter = "文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*",
Multiselect = true
};
if (dialog.ShowDialog() == true)
{
foreach (var file in dialog.FileNames)
{
// 處理選取的檔案
}
}
}
兩者用法幾乎相同,僅差異在命名空間與回傳值判斷(WinForms 用 DialogResult.OK,WPF 用 true)。
| 面向 | WinForms | WPF |
|---|---|---|
| 對話框外觀 | 傳統 Windows 樣式,隨作業系統版本 | 支援自訂樣式、模板化、DPI 感知 |
| 檔案對話框 | 舊版 Common Item Dialog (XP 風格) | Vista+ IFileDialog 介面,支援 Library、搜尋箱 |
| 非同步支援 | 無內建非同步 | 可搭配 Task/await 模式包裝 |
| 跨執行緒呼叫 | 需在 UI 執行緒 | 需在 UI 執行緒 (Dispatcher) |
IDisposable,建議使用 using 區塊;WPF 版本雖非強制,但良好習慣同樣適用。IDialogService),方便 Mock 測試。System.Windows.Forms 導致組件衝突、部署體積膨脹。PresentationFramework 只為用 WPF MessageBox,得不償失。InitialDirectory 未設定,導致預設開啟「文件庫」或系統目錄,體驗不佳。