在自定義控件的過程中,可以優先考慮從現有的控件中進行派生,並添加所需要的功能。(制作效果,當鼠標指針移動到控件時,控件顏色就會發生改變,當鼠標離開時就恢復原來的顏色)
首先添加一個新的類。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; namespace Contol顏色 { //[DefaultProperty("HoverColor")] //[Designer(typeof(ColourControl))] public class ColourControl : Control { #region //重寫該屬性以設置控件默認大小 protected override System.Drawing.Size DefaultSize { get { return new Size(100, 100); } } //當鼠標指針移動到控件區域內時的顏色 public Color HoverColor { get { return M_hoverColor; } set { M_hoverColor = value; Invalidate();//強制重新繪制 } } #endregion #region //該變量標識鼠標指針是否已經進入控件的區域 private bool isMouseEnter = false; //當鼠標進入控件區域后的背景顏色 Color M_hoverColor; #endregion #region 方法 protected override void OnMouseEnter(EventArgs e) { //標識鼠標指正已經進入區域 isMouseEnter = true; //強制重新繪制 Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseLeave(EventArgs e) { //標識鼠標指針是否已經離開控件 isMouseEnter = false; //強制重新繪制 Invalidate(); base.OnMouseLeave(e); } protected override void OnPaint(PaintEventArgs e) { //用於填充控件背景區域的畫刷 SolidBrush brush = new SolidBrush(BackColor); if (isMouseEnter) { brush.Color = HoverColor; } e.Graphics.FillRectangle(brush, e.ClipRectangle); //釋放畫刷資源 brush.Dispose(); } #endregion } }
在解決方案資源管理器窗口中設置:引用---->添加引用,勾選
點擊重新生成項目。找到