c# - 如何创建自定义消息框?

标签 c# winforms forms messagebox

我正在尝试使用我的控件制作自定义消息框。

public static partial class Msg : Form
{
    public static void show(string content, string description)
    {

    }
}

实际上我需要在这个窗体中放置一些控件(一个 gridview)并且我必须为这个窗口应用我自己的主题,所以我不想使用 MessageBox。我想从我的其他表单中调用它,比如

Msg.show(parameters);

我不想为此表单创建对象。

我知道我不能从 Form 类继承,因为它不是静态的。但是我想知道 MessageBox 是如何实现的,因为它是静态的。它被称为 MessageBox.show("Some message!");

现在我收到一个错误,因为不允许继承:

Static class 'MyFormName' cannot derive from type 'System.Windows.Forms.Form'. Static classes must derive from object

Screenshot of my form

MessageBox是如何实现的?

最佳答案

您的表单类不必是 static .事实上,静态类根本无法继承

相反,创建一个 internal派生自 Form 的表单类并提供 public static显示它的辅助方法

如果您不希望调用者甚至“知道”底层表单,则此静态方法可以在不同的类中定义

/// <summary>
/// The form internally used by <see cref="CustomMessageBox"/> class.
/// </summary>
internal partial class CustomMessageForm : Form
{
    /// <summary>
    /// This constructor is required for designer support.
    /// </summary>
    public CustomMessageForm ()
    {
        InitializeComponent(); 
    } 

    public CustomMessageForm (string title, string description)
    {
        InitializeComponent(); 

        this.titleLabel.Text = title;
        this.descriptionLabel.Text = description;
    } 
}

/// <summary>
/// Your custom message box helper.
/// </summary>
public static class CustomMessageBox
{
    public static void Show (string title, string description)
    {
        // using construct ensures the resources are freed when form is closed
        using (var form = new CustomMessageForm (title, description)) {
            form.ShowDialog ();
        }
    }
}

旁注:如 Jalal points out , 你不必上课 static为了拥有static其中的方法。但我仍然会将“帮助程序”类与实际表单分开,这样调用者就无法使用构造函数创建表单(当然,除非它们在同一个程序集中)。

关于c# - 如何创建自定义消息框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932792/

相关文章:

c# - 仅使用c# winform,不使用asp.netc#输入表单后如何检查用户是否登录

c# - 如何使用 Windows 窗体创建和连接自定义用户按钮/控件

javascript - 如何格式化使用表单发送的电子邮件的内容?

forms - Symfony2 - 为实体字段设置选定的值

c# - 使用 Gtk 检测双击#

c# - 有没有办法告诉我在运行时使用的是哪个枚举?

c# - 如何在主窗体之前显示辅助窗体?

C# udp 套接字没有收到整个消息

c# - 使用逗号和引号作为分隔符解析 csv 文件

javascript - 在不同的域上发布表单