65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 中 .NET Framework 4.5 的对话框消息

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (9投票s)

2020 年 4 月 13 日

CPOL

3分钟阅读

viewsIcon

23819

downloadIcon

736

编写自己的 Windows 对话框消息框的参考

目录

  1. 引言
  2. 在我们继续之前
  3. 实现
  4. 窗体设计
  5. 代码
    1. 结构
    2. 事件和方法
  6. 结论
  7. 历史

引言

在我开始编程的时候,我发现了标准 .NET Framework 库中的 MessageBox 类。这很令人兴奋,因为它允许我尝试用不同的方式来获取关于我的应用程序中正在发生的事情的信息。这很好,直到我在个人使用 Windows 时看到了一个特定的消息框。我最终了解到,这个消息框实际上被称为 TaskDialog,它是在 Windows Vista 中引入的。它顶部有蓝色文本,底部有一些较小的黑色文本。当时理解如何使用 TaskDialog 超出了我的技能范围,所以我决定尝试使用我当时掌握的技能来创建一个类似外观的对话框。

在这个项目中,我们将使用 Visual Studio 和 Designer 以及 C# 编写我们自己的对话框消息框。它将支持两种文本样式、三种按钮配置和六种图标配置。使用的图标来自 SystemIcons 类。

在我们继续之前

这并不是一个关于如何使用 Visual StudioC# 编程语言 的逐步教程,而是一个概述,说明了开发您自己的消息框所需的逻辑。代码部分的程序片段有很多注释,以帮助理解每一部分的作用。下面列出了假设您已经熟悉的主题

实现

以下是消息的实现。此代码将显示消息,就像它出现在文章开头图像中一样。

using DialogMessage;

if (DMessage.ShowMessage(

    // Window Title
    "Window Title",

    // Main Instruction
    "Want to learn how to write your own message box?",

    // Dialog buttons
    DMessage.MsgButtons.YesNo,

    // Dialog Icons
    DMessage.MsgIcons.Question,

    // Content
    "In this project we will learn the logic necessary " +
    "to write your own dialog message box in Windows")

    // Checks DialogResult of the button clicked by user
    == DialogResult.Yes)

    // Show the Windows standard MessageBox to test result
    MessageBox.Show("You clicked Yes!");

else

    MessageBox.Show("You clicked No!");

窗体设计

下图是 MainForm.Designer.cs 的窗体设计器视图,其中包含控件和一些重要的属性。需要注意的重要属性是 AnchorMaximumSizeFormBorderStyle

Anchor 确保 Form 上的控件在调整大小时正确移动。

LabelMaximumSize 确保文本不会溢出 Form,并将换行。

FormBorderStyle 设置为 FixedDialog,确保用户无法调整 Form 的大小,使其能够根据提供的文本量进行调整大小。

代码

结构

消息框分为两个主要文件;MainForm.csDialogMessage.cs

MainForm.cs 包含以下 Form.Load 事件

// Form.Load event
private void DialogMessage_Load(object sender, EventArgs e) 
{
      // Set the starting locations and sizes of the labels
      // Adjust the locations and sizes of the labels to properly show the information
}

DialogMessage.cs 包含以下三个代码块;一个 public static 方法和两个 enum

/// <summary>
/// A public static method with a return value of System.Windows.Forms.DialogResult
/// </summary>
/// <param name="_windowTitle"></param>
/// <param name="_mainInstruction"></param>
/// <param name="_msgButtons"></param>
/// <param name="_msgIcons"></param> // Optional parameter with default value of None
/// <param name="_content"></param> // Optional parameter with empty default value
/// <returns></returns>
public static DialogResult ShowMessage(string _windowTitle,
                                       string _mainInstruction, 
                                       MsgButtons _msgButtons,
                                       MsgIcons _msgIcons = MsgIcons.None,
                                       string _content = "") 
{
      // Set button and icon configurations and show the information to the user
}
// Message button enum for switch statement in ShowMessage
// This will set the properties of the form buttons and their DialogResult
public enum MsgButtons
{
      OK = 0,
      OKCancel = 1,
      YesNo = 2
}
// Message icon enum for switch statement in ShowMessage
// This will set the Image for the PictureBox
public enum MsgIcons
{
    None = 0,
    Question = 1,
    Info = 2,
    Warning = 3,
    Error = 4,
    Shield = 5
}

事件和方法

让我们进入每个代码块,看看它做了什么。

MainForm.cs 中的 Form.Load 事件

private void DialogMessage_Load(object sender, EventArgs e)
{
    // Once the ShowMessage function is called and the form appears
    // the code below makes the appropriate adjustments so the text appears properly

    // If no icon will be shown then shift the MainInstruction and Content 
    // left to an appropriate location

    // Adjust the MaximumSize to compensate for the shift left.
    if (msgIcon.Visible == false)
    {
        mainInstruction.Location = new Point(12, mainInstruction.Location.Y);
        mainInstruction.MaximumSize = new Size(353, 0);

        content.Location = new Point(12, content.Location.Y);
        content.MaximumSize = new Size(353, 0);
    }

    // Gets the Y location of the bottom of MainInstruction
    int mainInstructionBottom = mainInstruction.Location.Y + mainInstruction.Height;

    // Gets the Y location of the bottom of Content
    int contentBottom = content.Location.Y + content.Height;

    // Offsets the top of Content from the bottom of MainInstruction
    int contentTop = mainInstructionBottom + 18; // 18 just looked nice to me

    // Sets new location of the top of Content
    content.Location = new Point(content.Location.X, contentTop);

    if (content.Text == string.Empty)

        // If only MainInstruction is provided then make the form a little shorter
        Height += (mainInstruction.Location.Y + mainInstruction.Height) - 50;
    else
        Height += (content.Location.Y + content.Height) - 60;
}

DialogMessage.cs 中的 ShowMessage 方法

public static DialogResult ShowMessage(string _windowTitle,
                                        string _mainInstruction,
                                        MsgButtons _msgButtons,
                                        MsgIcons _msgIcons = MsgIcons.None,
                                        string _content = "")
{
    // Creates a new instance of MainForm so we can set the properties of the controls
    MainForm main = new MainForm();

    // Sets the initial height of the form
    main.Height = 157;

    // Sets Window Title
    main.Text = _windowTitle;

    // Sets MainInstruction
    main.mainInstruction.Text = _mainInstruction;

    // Sets Content
    main.content.Text = _content;

    // Sets the properties of the buttons based on which enum was provided
    switch (_msgButtons)
    {
        // Button1 is the left button
        // Button2 is the right button

        case MsgButtons.OK:
            
            main.Button1.Visible = false;
            main.Button2.DialogResult = DialogResult.OK;
            main.Button2.Text = "OK";
            main.AcceptButton = main.Button2; 
            main.Button2.TabIndex = 0;
            main.ActiveControl = main.Button2;

            break;

        case MsgButtons.OKCancel:

            main.Button1.DialogResult = DialogResult.OK;
            main.Button2.DialogResult = DialogResult.Cancel;
            main.Button1.Text = "OK";
            main.Button2.Text = "Cancel";
            main.AcceptButton = main.Button2; 
            main.Button1.TabIndex = 1;
            main.Button2.TabIndex = 0;
            main.ActiveControl = main.Button2;

            break;

        case MsgButtons.YesNo:

            main.Button1.DialogResult = DialogResult.Yes;
            main.Button2.DialogResult = DialogResult.No;
            main.Button1.Text = "Yes";
            main.Button2.Text = "No";
            main.AcceptButton = main.Button2; 
            main.Button1.TabIndex = 1;
            main.Button2.TabIndex = 0;
            main.ActiveControl = main.Button2;

            break;

        default:
            break;
    }

    // Sets the Image for the PictureBox based on which enum was provided
    if (_msgIcons != MsgIcons.None)
    {
        main.msgIcon.Visible = true;

        switch (_msgIcons)
        {
            case MsgIcons.Question:

                main.msgIcon.Image = SystemIcons.Question.ToBitmap();
                break;

            case MsgIcons.Info:

                main.msgIcon.Image = SystemIcons.Information.ToBitmap();
                break;

            case MsgIcons.Warning:

                main.msgIcon.Image = SystemIcons.Warning.ToBitmap();
                break;

            case MsgIcons.Error:

                main.msgIcon.Image = SystemIcons.Error.ToBitmap();
                break;

            case MsgIcons.Shield:

                main.msgIcon.Image = SystemIcons.Shield.ToBitmap();
                break;

            default:
                break;
        }
    }
    else
    {
        main.msgIcon.Visible = false;
    }

    // Shows the message and gets the result selected by the user
    return main.ShowDialog();
}

结论

我希望您发现这篇文章很有用。我意识到 CodeProject 上已经有一些关于消息框替代方案和 Windows TaskDialog(启发了这个项目)的包装器的深入文章,但是,我希望这成为学习如何编写您自己的参考资料。

历史

  • 2020 年 4 月 25 日
    • 添加了图标功能。使用的图标来自 SystemIcons 类。
  • 2020 年 4 月 18 日
    • 重新设计了代码,使用 static 类和方法。这消除了创建 DialogMessage 新实例的需要。
  • 2020 年 4 月 13 日
    • 初始版本
C# 中 .NET Framework 4.5 的对话框消息 - CodeProject - 代码之家
© . All rights reserved.