MessageBox

クラス階層

  • System.Object
    • System.Windows.Forms.MessageBox
MessageBox クラス (System.Windows.Forms) | MSDN

このクラスはSystem.Windows.Forms.dllアセンブリに含まれるため、コンソール アプリケーションから呼び出すにはSystem.Windows.Formsを参照に追加します。

Show()

メッセージ ボックスを表示できます。このダイアログボックスはモーダル ウィンドウであり、ユーザーによって閉じられるまで以降の操作がブロックされます。

public static DialogResult Show(
    string text,                            // メッセージ ボックスに表示するテキスト
    string caption,                         // タイトルバーに表示するテキスト
    MessageBoxButtons buttons,              // 表示するボタン
    MessageBoxIcon icon,                    // 表示するアイコン
    MessageBoxDefaultButton defaultButton,  // 既定のボタン
    MessageBoxOptions options,              // 表示オプション
    string helpFilePath,                    // ヘルプファイルのパス
    HelpNavigator navigator,                // 表示するヘルプファイルの要素
    Object param                            // ヘルプ トピックのID
)
MessageBox.Show メソッド (String, String, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String, HelpNavigator, Object) (System.Windows.Forms) | MSDN

MessageBoxのShow()メソッドには複数のオーバーロードがあり、

DialogResult Show( string text )
DialogResult Show( string text, string caption )
DialogResult Show( string text, string caption, MessageBoxButtons buttons )
DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon )
DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton )
DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options )

のように機能を追加していく形で実装されています。このうちtextだけを指定する形式では、

public static DialogResult Show(string text) {
    return ShowCore(null, text, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false);
}

のようの他の引数が指定されます。Show - MessageBox.cs

なおoptionsを指定しないと、コード分析で「MessageBoxOption を指定します」としてCA1300で警告されます。

MessageBoxButtons列挙型

列挙子 表示イメージ (Windows XP)
OK
OKCancel
AbortRetryIgnore
YesNoCancel
YesNo
RetryCancel
MessageBoxButtons 列挙型 (System.Windows.Forms) | MSDN

Cancelを含む形式は、Escの押下でDialogResult.Cancelを返します。もしEscに応答することを期待するならば、Cancelを含む形式とします。

処理に付随する操作があるとき、その操作を実行するか否か以外に、処理を取り消す (cancel) 選択があるときにYesNoCancelを用います。「いいえ」と「キャンセル」の違いって?:IT4コマ漫画 - ITmedia NEWS 有江敬寛 (2012/06/08)

MessageBoxIcon列挙型

列挙子 表示イメージ (Windows XP)
None  
Question  
Asterisk  
Information  
Exclamation  
Warning  
Hand  
Stop  
Error  
MessageBoxIcon 列挙型 (System.Windows.Forms) | MSDN

MessageBoxOptions列挙型

列挙子 数値 意味
DefaultDesktopOnly 131072 アクティブ デスクトップに表示する

The message box is displayed on the active desktop. This constant is similar to ServiceNotification, except that the system displays the message box only on the default desktop of the interactive window station. The application that displayed the message box loses focus, and the message box is displayed without using visual styles. For more information, see Rendering Controls with Visual Styles.

ServiceNotification 2097152 アクティブ デスクトップに表示する

The message box is displayed on the active desktop. The caller is a service notifying the user of an event. Show displays a message box on the current active desktop, even if there is no user logged on to the computer.

RightAlign 524288 テキストを右揃えで表示する
RtlReading 1048576 テキストを右から左へ読むように指定する
MessageBoxOptions Enum (System.Windows.Forms) | Microsoft Learn

フォント

テキストの表示にはシステムで設定されているフォントが使用され、これを指定する手段は提供されていません。よって必要ならば、独自にFormから実装します。c# - MessageBox.Show-- font change? - Stack Overflow

表示位置の変更

MessageBoxには表示時の位置を指定する機能はないため、Formから独自に作成します。

もしくはWin32 APIのSetWindowPos()で位置を移動します。 オーナーウィンドウの中央にメッセージボックスを表示する : C#プログラミング | iPentec Winforms-How can I make MessageBox appear centered on MainForm? - Stack Overflow

UIスレッド以外からの表示

UIスレッド以外から表示した場合は呼び出し側のコントロールはオーナーとはならず、背面に隠れてしまうことがあります。それが問題となるならば、UIスレッドに戻してから表示します。

// UIスレッドの操作はブロックされる。呼び出し側の背面に隠れることはない
MessageBox.Show("A");

Task.Run(() =>
{
    // UIスレッドの操作はブロックされない。呼び出し側の背面に隠れることがある
    MessageBox.Show("B");
    // MessageBox.Show(this, "B"); // InvalidOperationException「有効ではないスレッド間の操作: コントロールが作成されたスレッド以外のスレッドからコントロール '' がアクセスされました。」

    this.Invoke((MethodInvoker)delegate
    {
        // UIスレッドの操作はブロックされる。呼び出し側の背面に隠れることはない
        MessageBox.Show("C");
    });
});

メッセージ ボックスをプログラムにより閉じる

メッセージ ボックスはモーダル ウィンドウとして表示されるため、ユーザーによって閉じられるまで制御が戻りません。これを閉じる方法もありますが、プログラムにより閉じられる独自のFormを実装すべきです。c# - Force to close MessageBox programmatically - Stack Overflow

なおMessageBoxクラスはWin32のMessageBox関数を呼んでいるだけのため、これを拡張しても閉じられるようにはできません。ShowCore() - MessageBox.cs

参考

参考書

Microsoft Learnから検索