C#制作WinForm用户自定义控件实例教程
本文将教大家如何使用C#开发WinForm用户自定义控件,自定义控件有好多好处,下面请跟本文一同来学习下吧。
.Nt用户自定义控件继承UrControl类,设计很简单的,像平时在窗体上拖控件一样。
操作步骤:
1. 建立一个工程,添加用户控件。上海高中
2.在打开的窗体内输入控件名称,如:"ucButton",按确定按钮。接下来在空白区域拖放3个.Net控件。
如下图:
四级查分网站3.代码
C# code
/// <summary> /// C#.Net 设计用户自定义控件 /// </summary> /// </summary> [ToolboxBitmap(typeof(CustomControl.ucButton), "ucButton.bmp")] public partial class ucButton : UrControl { private bool _IsFocud = fal; //标记按钮是否为焦点状态 public ucButton() { InitializeComponent(); this.DoHideFocudTag(); 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; } t { _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 nder, EventArgs e) { //转移Click事件, 触发用户自定义事件 ifqashqai
(_OnButtonClick != null) _OnButtonClick(this, e); } private void lblCaption_MouDown(object nder, MouEventArgs e) { if (_IsFocud) { lblCaption.Font = new Font(lblCaption.Font.FontFamily,
lblCaption.Font.Size, FontStyle.Bold); } } private void
lblCaption_MouUp(object nder, MouEventArgs e) { if (_IsFocud) { lblCaption.Font = new Fo
nt(lblCaption.Font.FontFamily,
lblCaption.Font.Size, FontStyle.Regular); } } private void
ucButton_SizeChanged(object nder, EventArgs e) { lblUnderLine.Top = this.Height - 1; lblUnderLine.Width = this.Width - 15; } /// <summary> /// 还原按钮状态 /// </summary> public void DoHideFocudTag() { this.pictureBox1.Image =卡洛塔>贝尔机器人
global::vjsdn.CustomControl.Properties.Resources.GrayTag;
this.lblUnderLine.Visible = fal; lblCaption.ForeColor = Color.Black; } /// <summary> /// 设计按钮为焦点状态 /// </summary> public void DoShowFocudTag() { this.pictureBox1.Image =
global::vjsdn.CustomControl.Properties.Resources.FodTag;求职意向英文
wearsidethis.lblUnderLine.Visible = true; lblCaption.ForeColor = Color.Blue; } private void
ucButton_MouEnter(object if (this.Parent != null) { foreach (Control c in this.Parent.Controls) { if (c is ucButton) (c as ucButton).DoHideFocudTag(); } }
this.DoShowFocudTag(); _IsFocud = true; }w e
[EditorBrowsable(EditorBrowsableState.Always)] [Browsable(true)] [Description("")] public Label MyCaption { get { return lblCaption; } } private void lblCaption_MouEnter(object nder, EventArgs e)
{ this.ucButton_MouEnter(nder, e); }
4. 按F5编译项目,建立一个测试窗体,在控件工具栏会看到有个齿轮图标的项目。
figure在窗体上拖3个ucButton。
5.设置按钮标题及事件。
就这么简单,然后按F5运行下程序就可以看到自定义控件的效果了。