一、开发自定义控件
1、新建一个控件库
2、在界面上添加控件
这里加的是两个label,两个textbox,一个按钮
3、为自定义控件添加代码
namespace MyControls
{
public partial class UserPwdCheckControl: UserControl
{
//添加了一个事件
public event Action PwdRight;
public string UserName { get; set; }
public UserPwdCheckControl()
{
InitializeComponent();
if (!string.IsNullOrEmpty(UserName))
this.txtUserName.Text = UserName;
}
public UserPwdCheckControl(string userName)
{
InitializeComponent();
this.txtUserName.Text = userName;
}
private void btnCheck_Click(object sender, EventArgs e)
{
if (this.txtPwd.Text == "12345")
{
//密码正确时触发事件
PwdRight.Invoke();
}
}
}
}
4、编译生成dll
二、引用自定义控件
1、在工具栏中右键选择项
2、选择浏览,找到自己生成的dll文件
3、 将控件拖到界面上,并添加代码
namespace WindowsFormsApp2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
//添加对密码正确事件的监听
userPwdCheckControl1.PwdRight += UserPwdCheckControl1_PwdRight;
}
private void UserPwdCheckControl1_PwdRight()
{
MessageBox.Show("密码正确!");
}
}
}