System.Windows.MessageBox vs System.Windows.Forms.MessageBox

时间:2011-01-11 17:33:13

标签: c# .net wpf winforms messagebox

我无法找出两个消息框之间的主要区别。 System.Windows.MessageBoxSystem.Windows.Forms.MessageBox之间有什么区别?

4 个答案:

答案 0 :(得分:22)

System.Windows.MessageBox添加了WPF,并存在于WPF程序集(PresentationFramework.dll)中。

System.Windows.Forms.MessageBox已添加Windows窗体,并存在于Windows窗体程序集中。

如果您的程序是Windows窗体程序,我会使用后者(System.Windows.Forms.MessageBox),因为它不会引入对WPF的依赖。另一方面,如果您正在为WPF开发,我将使用System.Windows.MessageBox

答案 1 :(得分:9)

应该注意另外一点:

如果要在既不是Windows窗体应用程序也不是窗体应用程序(例如.NET控制台应用程序)的应用程序中显示消息框,则不应该将程序集引用拖入其中,因为它们似乎是常见的互联网上的口头禅。

相反,您应该使用并按如下方式调用User32:

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MessageBoxResult MessageBox(IntPtr hWnd, String text, String caption, int options);

/// <summary>
/// Flags that define appearance and behaviour of a standard message box displayed by a call to the MessageBox function.
/// </summary>
[Flags]
public enum MessageBoxOptions : uint
{
    Ok = 0x000000,
    OkCancel = 0x000001,
    AbortRetryIgnore = 0x000002,
    YesNoCancel = 0x000003,
    YesNo = 0x000004,
    RetryCancel = 0x000005,
    CancelTryContinue = 0x000006,

    IconHand = 0x000010,
    IconQuestion = 0x000020,
    IconExclamation = 0x000030,
    IconAsterisk = 0x000040,
    UserIcon = 0x000080,
    IconWarning = IconExclamation,
    IconError = IconHand,
    IconInformation = IconAsterisk,
    IconStop = IconHand,
    DefButton1 = 0x000000,
    DefButton2 = 0x000100,
    DefButton3 = 0x000200,
    DefButton4 = 0x000300,

    ApplicationModal = 0x000000,
    SystemModal = 0x001000,
    TaskModal = 0x002000,

    Help = 0x004000, //Help Button
    NoFocus = 0x008000,

    SetForeground = 0x010000,
    DefaultDesktopOnly = 0x020000,
    Topmost = 0x040000,
    Right = 0x080000,
    RTLReading = 0x100000,
}

/// <summary>
/// Represents possible values returned by the MessageBox function.
/// </summary>
public enum MessageBoxResult : uint
{
    Ok = 1,
    Cancel,
    Abort,
    Retry,
    Ignore,
    Yes,
    No,
    Close,
    Help,
    TryAgain,
    Continue,
    Timeout = 32000
}

var result = User32.MessageBox(IntPtr.Zero, "Debugging Break", "Your Console Application", (int)User32.MessageBoxOptions.Ok);

答案 2 :(得分:2)

两者基本上都做同样的事情,除了system.windows.messagebox是WPF而system.windows.forms.messagebox是Windows Forms。如果你使用WPF使用前者,对WinForms使用后者。

答案 3 :(得分:2)

据我所知,两者最终都会调用相同的低级别Windows API。