Net使用者自訂控制項繼承UserControl類,設計很簡單的,像平時在表單上拖控制項一樣。
下面跟著我一步步做:
1. 建立一個工程,添加使用者控制項。
2.在開啟的表單內輸入控制項名稱,如:"ucButton",按確定按鈕。接下來在空白地區拖放3個.Net控制項。
如:
3.編碼
代碼
/// <summary>
/// C#.Net 設計使用者自訂控制項
/// C#製作使用者自訂控制項 (by www.vjsdn.net 易學網)
/// </summary>
/// </summary>
[ToolboxBitmap(typeof(CustomControl.ucButton), "ucButton.bmp")]
public partial class ucButton : UserControl
{
private bool _IsFocused = false; //標記按鈕是否為焦點狀態
public ucButton()
{
InitializeComponent();
this.DoHideFocusedTag();
this.MyCatpionText = this.Name;
}
private EventHandler _OnButtonClick = null;
private string _MyCatpionText = "ucButton1";
/// <summary>
/// 按鈕標題
/// </summary>
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[DefaultValue("ucButton1")]
public string MyCatpionText
{
get { return _MyCatpionText; }
set { _MyCatpionText = value; lblCaption.Text = _MyCatpionText; }
}
/// <summary>
/// 使用者自訂Click事件
/// </summary>
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
public event EventHandler OnButtonClick
{
add { _OnButtonClick += new EventHandler(value); }
remove { _OnButtonClick -= new EventHandler(value); }
}
private void lblCaption_Click(object sender, EventArgs e)
{
//轉移Click事件, 觸發使用者自訂事件
if (_OnButtonClick != null) _OnButtonClick(this, e);
}
private void lblCaption_MouseDown(object sender, MouseEventArgs e)
{
if (_IsFocused)
{
lblCaption.Font = new Font(lblCaption.Font.FontFamily, lblCaption.Font.Size, FontStyle.Bold);
}
}
private void lblCaption_MouseUp(object sender, MouseEventArgs e)
{
if (_IsFocused)
{
lblCaption.Font = new Font(lblCaption.Font.FontFamily, lblCaption.Font.Size, FontStyle.Regular);
}
}
private void ucButton_SizeChanged(object sender, EventArgs e)
{
lblUnderLine.Top = this.Height - 1;
lblUnderLine.Width = this.Width - 15;
}
/// <summary>
/// 還原按鈕狀態
/// </summary>
public void DoHideFocusedTag()
{
this.pictureBox1.Image = global::vjsdn.CustomControl.Properties.Resources.GrayTag;
this.lblUnderLine.Visible = false;
lblCaption.ForeColor = Color.Black;
}
/// <summary>
/// 設計按鈕為焦點狀態
/// </summary>
public void DoShowFocusedTag()
{
this.pictureBox1.Image = global::vjsdn.CustomControl.Properties.Resources.FosedTag;
this.lblUnderLine.Visible = true;
lblCaption.ForeColor = Color.Blue;
}
private void ucButton_MouseEnter(object sender, EventArgs e)
{
if (this.Parent != null)
{
foreach (Control c in this.Parent.Controls)
{
if (c is ucButton) (c as ucButton).DoHideFocusedTag();
}
}
this.DoShowFocusedTag();
_IsFocused = true;
}
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[Description("")]
public Label MyCaption
{
get { return lblCaption; }
}
private void lblCaption_MouseEnter(object sender, EventArgs e)
{
this.ucButton_MouseEnter(sender, e);
}
}
4. 按F5編譯項目,建立一個測試表單,在控制項工具欄會看到有個齒輪表徵圖的項目。
在表單上拖3個ucButton。
5.設定按鈕標題及事件。
6.運行程式