HOW TO:建立自訂影像按鈕控制項

更新:2007 年 11 月

若要以影像來建立按鈕,您必須建立從 Windows Form Control 類別衍生的自訂控制項。

若要以影像來建立按鈕

  1. 建立從 System.Windows.Forms.Control 類別衍生的類別。

  2. 針對要顯示已按下和未按下狀態的按鈕影像,在類別中定義屬性。

  3. 使用 Invalidate 方法,使表單在按下按鈕時重新繪製。

  4. 覆寫 OnPaint 方法,以適當的影像來繪製自訂控制項。

範例

這個範例包含了可定義 PictureButton 自訂控制項的類別。此類別會在表單上建立控制項的執行個體,並定義控制項所用的點陣圖。

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class PictureButtonDemo
    Inherits System.Windows.Forms.Form

    Friend WithEvents PictureButton1 As New PictureButton

    Public Sub New()

        ' Display the OK close button.
        Me.MinimizeBox = False
        Me.Text = "Picture Button Demo"

        ' Create an instance of the PictureButton custom control.
        With PictureButton1
            .Parent = Me
            .Bounds = New Rectangle(10, 30, 150, 30)
            .ForeColor = Color.White
            .BackgroundImageValue = MakeBitmap(Color.Blue, _
                PictureButton1.Width, PictureButton1.Height)
            .PressedImageValue = MakeBitmap(Color.LightBlue, _
                PictureButton1.Width, PictureButton1.Height)
            .Text = "Click Me"
        End With
    End Sub

    ' Clean up any resources being used.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        MyBase.Dispose(disposing)
    End Sub

    ' Create a bitmap object and fill it with the specified color.   
    ' To make it look like a custom image, draw an ellipse in it.
    Function MakeBitmap(ByVal ButtonColor As Color, ByVal width As Integer, _
        ByVal height As Integer) As Bitmap

        Dim bmp As New Bitmap(width, height)
        Dim g As Graphics = Graphics.FromImage(bmp)
        g.FillRectangle(New SolidBrush(ButtonColor), 0, 0, bmp.Width, bmp.Height)
        g.DrawEllipse(New Pen(Color.LightGray), 3, 3, width - 6, height - 6)
        g.Dispose()

        Return bmp
    End Function

    Shared Sub Main()
        Application.Run(New PictureButtonDemo)
    End Sub

    ' Because PictureButton inherits from Control, 
    ' you can use the default Click event.
    Private Sub PictureButton1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles PictureButton1.Click

        'Add code here to respond to button click. 

    End Sub

End Class

'Button with an image custom control.
Public Class PictureButton
    Inherits Control

    Private backgroundImg As Image
    Private pressedImg As Image
    Private pressed As Boolean = False

    ' Property for the background image to be drawn behind the button text.
    Public Property BackgroundImageValue() As Image
        Get
            Return Me.backgroundImg
        End Get
        Set(ByVal Value As Image)
            Me.backgroundImg = Value
        End Set
    End Property

    ' Property for the background image to be drawn behind the button text when
    ' the button is pressed.
    Public Property PressedImageValue() As Image
        Get
            Return Me.pressedImg
        End Get
        Set(ByVal Value As Image)
            Me.pressedImg = Value
        End Set
    End Property

    ' When the mouse button is pressed, set the "pressed" flag to true
    ' and ivalidate the form to cause a repaint.  The .NET Compact Framework
    ' sets the mouse capture automatically.
    Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
        Me.pressed = True
        Me.Invalidate()
        MyBase.OnMouseDown(e)
    End Sub

    ' When the mouse is released, reset the "pressed" flag
    ' and invalidate to redraw the button in the unpressed state.
    Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
        Me.pressed = False
        Me.Invalidate()
        MyBase.OnMouseUp(e)
    End Sub 

    ' Override the OnPaint method to draw the background image and the text.
    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        If Me.pressed AndAlso (Me.pressedImg IsNot Nothing) Then
            e.Graphics.DrawImage(Me.pressedImg, 0, 0)
        Else
            e.Graphics.DrawImage(Me.backgroundImg, 0, 0)
        End If

        ' Draw the text if there is any.
        If Me.Text.Length > 0 Then
            Dim size As SizeF = e.Graphics.MeasureString(Me.Text, Me.Font)

            ' Center the text inside the client area of the PictureButton.
            e.Graphics.DrawString(Me.Text, Me.Font, New SolidBrush(Me.ForeColor), _
                (Me.ClientSize.Width - size.Width) / 2, _
                (Me.ClientSize.Height - size.Height) / 2)
        End If

        ' Draw a border around the outside of the   
        ' control to look like Pocket PC buttons.
        e.Graphics.DrawRectangle(New Pen(Color.Black), 0, 0, _
            Me.ClientSize.Width - 1, Me.ClientSize.Height - 1)

        MyBase.OnPaint(e)
    End Sub
End Class
using System;
using System.Drawing;
using System.Windows.Forms;

namespace PictureButton
{
    public class PictureButtonDemo : System.Windows.Forms.Form
    {
        int clickCount = 0;

        // Create a bitmap object and fill it with the specified color.   
        // To make it look like a custom image, draw an ellipse in it.
        Bitmap MakeBitmap(Color color, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.FillRectangle(new SolidBrush(color), 0, 0, bmp.Width, bmp.Height);
            g.DrawEllipse(new Pen(Color.DarkGray), 3, 3, width - 6, height - 6);
            g.Dispose();

            return bmp;
        }

        // Create a new PictureButton control and hook up its properties.
        public PictureButtonDemo()
        {
            InitializeComponent();

            // Display the OK close button.
            this.MinimizeBox = false;

            PictureButton button = new PictureButton();
            button.Parent = this;
            button.Bounds = new Rectangle(10, 30, 150, 30);
            button.ForeColor = Color.White;
            button.BackgroundImage = MakeBitmap(Color.Blue, button.Width, button.Height);
            button.PressedImage = MakeBitmap(Color.LightBlue, button.Width, button.Height);
            button.Text = "click me";
            button.Click +=new EventHandler(button_Click);
        }

        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        }

        private void InitializeComponent()
        {
            this.Text = "Picture Button Demo";
        }

        static void Main() 
        {
            Application.Run(new PictureButtonDemo());
        }

        // Since PictureButton inherits from Control, we can just use the default
        // Click event that Control supports.
        private void button_Click(object sender, EventArgs e)
        {
            this.Text = "Click Count = " + ++this.clickCount;
        }
    }

    // This code shows a simple way to have a 
    // button-like control that has a background image.
    public class PictureButton : Control
    {
        Image backgroundImage, pressedImage;
        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;
            }
        }

        // Property for the background image to be drawn behind the button text when
        // the button is pressed.
        public Image PressedImage
        {
            get
            {
                return this.pressedImage;
            }
            set
            {
                this.pressedImage = 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)
        {
            if(this.pressed && this.pressedImage != null)
                e.Graphics.DrawImage(this.pressedImage, 0, 0);
            else
                e.Graphics.DrawImage(this.backgroundImage, 0, 0);

            // Draw the text if there is any.
            if(this.Text.Length > 0)
            {
                SizeF size = e.Graphics.MeasureString(this.Text, this.Font);

                // Center the text inside the client area of the PictureButton.
                e.Graphics.DrawString(this.Text,
                    this.Font,
                    new SolidBrush(this.ForeColor),
                    (this.ClientSize.Width - size.Width) / 2,
                    (this.ClientSize.Height - size.Height) / 2);
            }

            // Draw a border around the outside of the 
            // control to look like Pocket PC buttons.
            e.Graphics.DrawRectangle(new Pen(Color.Black), 0, 0, 
                this.ClientSize.Width - 1, this.ClientSize.Height - 1);

            base.OnPaint(e);
        }
    }
}

編譯程式碼

這個範例需要下列命名空間的參考:

請參閱

概念

自訂控制項開發

其他資源

.NET Compact Framework 中的 Windows Form 控制項