如何在自定义控件的属性中列出所有形式的解决方案资源管理器



我创建了一个登录验证自定义控件。它有两个名为usernamepassword的属性,当包含在项目中时,它们会显示在属性窗口中。

我想创建一个属性,它将以类似ComboBox的方式向属性窗口显示所有表单列表,这样项目程序员就可以指定登录成功时打开的表单。自定义控件有两个文本框和一个按钮。我该怎么做?

namespace WindowsFormsApplication18
{
    public partial class UserControl1 : UserControl
    {
        private string uname=null;
        private string pword=null;
        public string username
        {
            get
            {
                return uname;
            }
            set
            {
                uname = value;
            }
        }
        public string password
        {
            get
            {
                return pword;
            }
            set
            {
                pword=value;
            }
        }

        public UserControl1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == username && textBox2.Text == password)
            {
                MessageBox.Show("login successful");
            }
            else
                MessageBox.Show("wrong password");
        }
    }
}

以便项目程序员可以指定在成功登录时打开哪个表单

这实际上不是用户控制的任务。也许程序员想在成功登录后做其他事情。

创建一个LoggedIn事件,在成功登录时激发该事件,并从使用控件的代码中订阅该事件。然后,程序员可以在事件处理程序中按照自己的意愿进行操作。

要获取当前执行的Module中的所有Forms,可以执行以下操作:

//Must add using System.Reflection; first    
public class LoginForm : Form {
  public LoginForm(){
     InitializeComponent(); 
     Load += (s,e) => {
        forms = GetAllForms();
        comboBox1.DataSource = forms;
        comboBox1.DisplayMember = "Text";//Show the caption
     }; 
  }
  List<Form> forms;
  public List<Form> GetAllForms(){
    List<Form> forms = new List<Form>();
    foreach (Type t in Assembly.GetExecutingAssembly().GetModules()[0].GetTypes())
    {
      if (t == GetType()) continue;//Don't add LoginForm
      if (t.IsSubclassOf(typeof(Form)))
      {
         forms.Add((Form)t.GetConstructor(Type.EmptyTypes).Invoke(null));
      }
    }
    return forms;
  }
  private void button1_Click(object sender, EventArgs e)
  {
        if (textBox1.Text == username && textBox2.Text == password)
        {
            MessageBox.Show("login successful");
            //Show the selected form
            forms[comboBox1.SelectedIndex].Show();
        }
        else
            MessageBox.Show("wrong password");
  }
}

相关内容