MessageBox與DialogResult的用法
MessageBox有兩種不同的命名空間分別是
常存在於WPF專案的System.Windows.MessageBox與
常存在於Windows Form專案的System.Windows.Forms.MessageBox。
個人認為System.Windows.MessageBox比較好理解
不囉嗦,直接看程式碼最快
一、System.Windows.MessageBox程式範例
using System.Windows;
namespace LearningMessageBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("YES or NO", "請選擇", MessageBoxButton.YesNoCancel);
if (MessageBoxResult.Yes == result)
{
MessageBox.Show("你選擇了YES");
}
else if (MessageBoxResult.No == result)
{
MessageBox.Show("你選擇了NO");
}
}
}
}
二、System.Windows.Forms.MessageBox程式範例
using System;
using System.Windows.Forms;
namespace WindowsFormsLearningMessageBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("YES or NO", "請選擇", MessageBoxButtons.YesNoCancel);
if (DialogResult.Yes == result)
{
MessageBox.Show("你選擇了YES");
}
else if (DialogResult.No == result)
{
MessageBox.Show("你選擇了NO");
}
}
}
}
我曾看過有人不知什麼原因會同時使用System.Windows.MessageBox與
System.Windows.Forms.MessageBox,可能是要比較兩方法不同之處吧,
此時呼叫MessageBox方法編譯器就無法判斷是呼叫哪個命名空間的方法,
此時可用替代命名空間的別名解決如,
using SystemWindows = System.Windows;
using WindowsForms = System.Windows.Forms;
三、DialogResult程式範例
-
Imports System.IO
-
-
Public Class Form1
-
-
-
Private Sub btn選擇檔案_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn選擇檔案.Click
-
OpenFileDialog1.Title = "選擇檔案"
-
OpenFileDialog1.Filter = "TXT |*.txt"
-
OpenFileDialog1.InitialDirectory = Directory.GetCurrentDirectory
-
OpenFileDialog1.FileName = ""
-
-
OpenFileDialog1.Multiselect = False
-
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
-
txt選擇檔案路徑.Text = OpenFileDialog1.FileName
-
End If
-
End Sub
-
-
Private Sub btn儲存檔案_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn儲存檔案.Click
-
SaveFileDialog1.Title = "儲存檔案"
-
SaveFileDialog1.Filter = "TXT |*.txt"
-
SaveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory
-
SaveFileDialog1.FileName = ""
-
-
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
-
txt選擇儲存路徑.Text = SaveFileDialog1.FileName
-
End If
-
End Sub
-
End Class
System.Windows.Forms.MessageBox方法會使用到DialogResult屬性,
而OpenFileDialog也會用到DialogResult屬性,以至於讓人覺得有點雜亂。