如何创建自定义MessageBox?

Sen*_*cob 12 c# forms messagebox winforms

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

实际上我需要在这个窗体中放置一些控件(gridview),我必须在这个窗口中应用我自己的主题,所以我不想使用MessageBox.我想从我的其他形式这样称呼它

Msg.show(parameters);
Run Code Online (Sandbox Code Playgroud)

我不想为这个表单创建一个对象.

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

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

静态类'MyFormName'不能从类型'System.Windows.Forms.Form'派生.静态类必须从对象派生

我的表格截图

MessageBox那么如何实施?

Dan*_*mov 21

您的表单类不需要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 ();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

旁注:正如Jalal 指出的那样,你不必static为了在其中设置static方法而创建一个类.但我仍然会将"帮助器"类与实际表单分开,这样调用者就无法使用构造函数创建表单(除非它们当然在同一个程序集中).


Lio*_*ana 5

您不需要该类是静态的.做一些像:

public partial class Msg : Form
{
    public static void show(string content, string description)
    {
         Msg message = new Msg(...);
         message.show();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • -1因为你没有释放资源(而且`Show`不是模态的,你应该调用`ShowDialog`). (4认同)