Complete example for a UserControl:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_UserControl
{
public partial class Form1 : Form
{
MyCtl ctl = new MyCtl();
Color ctlDefaultColor;
public Form1()
{
InitializeComponent();
InitOthers();
}
private void InitOthers()
{
this.SuspendLayout();
this.ctl.Left = 10;
this.ctl.Top = 10;
this.Controls.Add(ctl);
this.ctl.MouseEnter += ctl_MouseEnter;
this.ctl.MouseLeave += ctl_MouseLeave;
this.ctlDefaultColor = this.ctl.ForeColor;
this.ResumeLayout(false);
this.PerformLayout();
}
void ctl_MouseLeave(object sender, EventArgs e)
{
this.ctl.ForeColor = this.ctlDefaultColor;
}
void ctl_MouseEnter(object sender, EventArgs e)
{
this.ctl.ForeColor = Color.Yellow;
}
}
public class MyCtl : UserControl
{
Label lbl;
Button btn;
public MyCtl()
{
this.Initialize();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
private void Initialize()
{
this.SuspendLayout();
this.lbl = new Label();
this.lbl.Left = 10;
this.lbl.Top = 10;
this.lbl.Text = "There exists a label here";
this.Controls.Add(this.lbl);
this.btn = new Button();
this.btn.Left = 10;
this.btn.Top += this.lbl.Bottom + 10;
this.btn.Text = "My Button";
this.Controls.Add(this.btn);
this.ResumeLayout(false);
}
}
}
And documentation:
UserControl Class[
^]