C# PicBtn Control 图形按钮

2019-04-15 14:59发布

  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Demo { public class PicBtn : Control, IDisposable // 图形按钮 { [DllImportAttribute("user32")] static extern int SetWindowLong(IntPtr hWnd, int nlndex, IntPtr dwNewStyle); [DllImportAttribute("user32")] static extern int CallWindowProc(int hWinProc, int hWND, int Msg, int wParam, int lParam); int _hWinProc = 0; MSG _MSG = null; EventHandler _Draw = null; const int GWL_WNDPROC = -4, WM_MOUSEFIRST = 512, WM_SHOWWINDOW = 24, WM_MOUSELEAVE = 675, WM_LBUTTONDOWN = 513, WM_LBUTTONUP = 514, WM_PAINT = 15; delegate int MSG(int hWnd, int Msg, int wParam, int lParam); public PicBtn() { this._MSG = (hWnd, Msg, wParam, lParam) => { switch (Msg) { case WM_MOUSEFIRST: this._Draw(1, null); break; case WM_MOUSELEAVE: this._Draw(0, null); break; case WM_LBUTTONDOWN: this._Draw(2, null); break; case WM_LBUTTONUP: this._Draw(1, null); break; } return CallWindowProc(this._hWinProc, hWnd, Msg, wParam, lParam); }; GC.SuppressFinalize(this._MSG); GCHandle.Alloc(this._MSG); this._hWinProc = SetWindowLong(this.Handle, GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(this._MSG)); this._Draw = (sender, e) => { if (!(sender is int)) { return; } using (var _g = this.CreateGraphics()) { var x = (int)sender; var client = this.ClientSize; if (!this.Enabled) { _g.DrawImageUnscaled(this._dpic, 0, 0, client.Width, client.Height); return; } Image _pic = null; switch (x) { case 0: _pic = this._npic; break; case 1: _pic = this._apic; break; case 2: _pic = this._ppic; break; } if (_pic == null) { return; } using (_pic = _pic.GetThumbnailImage(client.Width, client.Height, null, IntPtr.Zero)) { _g.DrawImageUnscaled(_pic, 0, 0, client.Width, client.Height); } } }; } Image _npic, _apic, _ppic, _dpic; [Description("正常图片"), Category("界面"), DefaultValue(typeof(Image), "null"), Browsable(true)] public Image npic { get { return this._npic; } set { this._npic = value; } } [Description("点燃图片"), Category("界面"), DefaultValue(typeof(Image), "null"), Browsable(true)] public Image apic { get { return this._apic; } set { this._apic = value; } } [Description("按下图片"), Category("界面"), DefaultValue(typeof(Image), "null"), Browsable(true)] public Image ppic { get { return this._ppic; } set { this._ppic = value; } } [Description("禁止图片"), Category("界面"), DefaultValue(typeof(Image), "null"), Browsable(true)] public Image dpic { get { return this._dpic; } set { this._dpic = value; } } } }
  // 上述代码不过只是简单的做一个图形按钮,此代码只做参考