C# Windows應用窗體使用者自定義控制元件--開關實現
阿新 • • 發佈:2019-01-08
先準備了兩個好看的開關圖片:
將圖片資源匯入專案
開啟Properties下Resources.rex:
選擇影象:
新增現有檔案:(將準備好的圖片新增)
新增完成,可以看到多了一個Resources資料夾,裡面就是我們剛剛新增的圖片:
自定義使用者控制元件
在專案右鍵新增使用者控制元件:
輸入名稱:
進入程式碼:
在建構函式中設定雙緩衝和背景透明以及控制元件大小。
public SwitchTest()
{
InitializeComponent();
this .SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true );
this.SetStyle(ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
this.Cursor = Cursors.Hand;
this.Size = new Size(87, 27);
}
定義一個公共屬性來標誌開關
bool isSwitch = false;
重寫OnPaint
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics ;
Rectangle rec = new Rectangle(0, 0, this.Size.Width, this.Size.Height);
if (isSwitch)
{
g.DrawImage(Properties.Resources.switchon, rec);
}
else
{
g.DrawImage(Properties.Resources.switchoff, rec);
}
}
重寫滑鼠點選
protected override void OnMouseClick(MouseEventArgs e)
{
isSwitch = !isSwitch;
this.Invalidate();
base.OnMouseClick(e);
}
此時使用者自定義控制元件完成,來測試一下。
先生成解決方案:
生成解決方案完成,到一個form設計,你會發現工具箱多了我們剛剛的使用者自定義控制元件:
拖拽一個放到form上:
執行,點選: