Wince下實現ImageButton

咱們在winform中給按鈕設置個背景圖片超級簡單,是不?但是在wince下面就沒那麼簡單了,下面我來介紹一種方式來實現ImageButton。web

實現思路是從新寫一個usercontrol就ok。具體的實現方式以下:ide

/IotButton是咱們新控件的名字,具體的能夠本身定義 
public partial class IotButton : UserControl 
    {
        public IotButton()
        {
            InitializeComponent();
        }
 
        Image backgroundImage;
        bool pressed = false;
 
        // Property for the background image to be drawn behind the button text.  
        public Image BackgroundImage
        {
            get
            {
                return this.backgroundImage;
            }
            set
            {
                this.backgroundImage = value;
            }
        }
        // When the mouse button is pressed, set the "pressed" flag to true   
        // and invalidate the form to cause a repaint.  The .NET Compact Framework   
        // sets the mouse capture automatically.  
        protected override void OnMouseDown(MouseEventArgs e)
        {
            this.pressed = true;
            this.Invalidate();
            base.OnMouseDown(e);
        }
 
        // When the mouse is released, reset the "pressed" flag   
        // and invalidate to redraw the button in the unpressed state.  
        protected override void OnMouseUp(MouseEventArgs e)
        {
            this.pressed = false;
            this.Invalidate();
            base.OnMouseUp(e);
        }
 
        // Override the OnPaint method to draw the background image and the text.  
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(SystemColors.ActiveCaption), e.ClipRectangle);
 
            if (this.backgroundImage != null)
            {
                ImageAttributes attr = new ImageAttributes();
                attr.SetColorKey(Color.Magenta, Color.Magenta);
 
                if (this.pressed)
                    e.Graphics.DrawImage(this.backgroundImage, this.ClientRectangle, 0, 0, this.backgroundImage.Width, this.backgroundImage.Height, GraphicsUnit.Pixel, attr);
                else
                    e.Graphics.DrawImage(this.backgroundImage, this.ClientRectangle, 0, 0, this.backgroundImage.Width, this.backgroundImage.Height, GraphicsUnit.Pixel, attr);
 
            }
 
            base.OnPaint(e);
        }
    }

 這裏爲何要實現一個新的UserControl而不是基於Button呢?具體緣由是這樣的,由於Button中沒有Paint事件,沒有MouseUP MouseDown MouseMove等事件所以不能很好的實現,有圖有證據哦?this

看看咱們自定義的按鈕的事件和屬性吧:spa

總結

上面的方式實現了在wince下自定義一個能夠放image的控件,具體的不一樣咱們能夠對比上面的兩圖獲得。但願對你們有幫助哦。3d

相關文章
相關標籤/搜索