C#.Net用户自定义控件制作教程
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Net用户自定义控件继承UserControl类,设计很简单的,像平时在窗体上拖控件一样。
下面跟着我一步步做:
1. 建立一个工程,添加用户控件。
2.在打开的窗体内输入控件名称,如:"ucButton",按确定按钮。接下来在空白区域拖放3个.Net控件。
如下图:
3.编码
代码
///
/// C#.Net 设计用户自定义控件
/// C#制作用户自定义控件 (by 易学网)
///
///
[ToolboxBitmap(typeof(CustomControl.ucButton), "ucButton.bmp")]
public partial class ucButton : UserControl
{
private bool _IsFocused = false; //标记按钮是否为焦点状态
public ucButton()
{
InitializeComponent();
this.DoHideFocusedTag();
this.MyCatpionText = ;
}
private EventHandler _OnButtonClick = null;
private string _MyCatpionText = "ucButton1";
///
///按钮标题
///
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[DefaultValue("ucButton1")]
public string MyCatpionText
{
get { return _MyCatpionText; }
set { _MyCatpionText = value; lblCaption.Text = _MyCatpionText; } }
///
///用户自定义Click事件
///
[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;
}
///
///还原按钮状态
///
public void DoHideFocusedTag()
{
this.pictureBox1.Image = global::vjsdn.CustomControl.Properties.Resources.GrayTag;
this.lblUnderLine.Visible = false;
lblCaption.ForeColor = Color.Black;
}
///
///设计按钮为焦点状态
///
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);
}
}