How to create a custom MessageBox?

后端 未结 4 1220
星月不相逢
星月不相逢 2020-11-27 06:09

I\'m trying to make a custom message box with my controls.

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


        
4条回答
  •  盖世英雄少女心
    2020-11-27 07:09

    Your form class needs not to be static. In fact, a static class cannot inherit at all.

    Instead, create an internal form class that derives from Form and provide a public static helper method to show it.

    This static method may be defined in a different class if you don't want the callers to even “know” about the underlying form.

    /// 
    /// The form internally used by  class.
    /// 
    internal partial class CustomMessageForm : Form
    {
        /// 
        /// This constructor is required for designer support.
        /// 
        public CustomMessageForm ()
        {
            InitializeComponent(); 
        } 
    
        public CustomMessageForm (string title, string description)
        {
            InitializeComponent(); 
    
            this.titleLabel.Text = title;
            this.descriptionLabel.Text = description;
        } 
    }
    
    /// 
    /// Your custom message box helper.
    /// 
    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 ();
            }
        }
    }
    

    Side note: as Jalal points out, you don't have to make a class static in order to have static methods in it. But I would still separate the “helper” class from the actual form so the callers cannot create the form with a constructor (unless they're in the same assembly of course).

提交回复
热议问题