1. 程式人生 > >C# Windows應用窗體使用者自定義控制元件--開關實現

C# Windows應用窗體使用者自定義控制元件--開關實現

先準備了兩個好看的開關圖片:
這裡寫圖片描述

將圖片資源匯入專案
開啟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上:
這裡寫圖片描述
執行,點選:
這裡寫圖片描述