方法 : グラデーションの塗りつぶしを表示します。

[このドキュメントはプレビュー版であり、後のリリースで変更されることがあります。 空白のトピックは、プレースホルダーとして挿入されています。]

グラデーションの塗りつぶしを表示し、カラフルな見栄えのグラフィックスをアプリケーションに追加できます。 カスタム コントロールでは、フォームの背景としてに、グラデーション塗りつぶしを表示するコード例を次に示します。

プロシージャ

グラデーションの塗りつぶしを表示するには

  1. Visual Studio でスマート デバイス プロジェクトを作成します。

  2. Gradientfill GradientFilledButton クラスとプロジェクトに追加します。

                                  NotInheritable
                                  Public
                                  Class GradientFill
    
        ' This method wraps the PInvoke to GradientFill.    ' Parmeters:    '  gr - The Graphics object we are filling    '  rc - The rectangle to fill    '  startColor - The starting color for the fill    '  endColor - The ending color for the fill    '  fillDir - The direction to fill    '    ' Returns true if the call to GradientFill succeeded; false    ' otherwise.PublicSharedFunction Fill(ByVal gr As Graphics, ByVal rc As Rectangle, ByVal startColor As Color, _
            ByVal endColor As Color, ByVal fillDir As FillDirection) AsBoolean
            ' Initialize the data to be used in the call to GradientFill.Dim tva(1) As Win32Helper.TRIVERTEX
            tva(0) = New Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor)
            tva(1) = New Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor)
            Dim gra() As Win32Helper.GRADIENT_RECT = {New Win32Helper.GRADIENT_RECT(0, 1)}
    
            ' Get the hDC from the Graphics object.Dim hdc As IntPtr = gr.GetHdc()
    
            ' PInvoke to GradientFill.Dim b AsBoolean
    
            b = Win32Helper.GradientFill(hdc, tva, CType(tva.Length, System.Int32), gra, CType(gra.Length, System.Int32), CType(fillDir, System.Int32))
    
            System.Diagnostics.Debug.Assert(b, String.Format("GradientFill failed: {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()))
    
            ' Release the hDC from the Graphics object.
            gr.ReleaseHdc(hdc)
    
            Return b
    
        EndFunction
        ' The direction to the GradientFill will followPublicEnum FillDirection
    
            ' The fill goes horizontally
            LeftToRight = Win32Helper.GRADIENT_FILL_RECT_H
    
            ' The fill goes vertically
            TopToBottom = Win32Helper.GRADIENT_FILL_RECT_V
        EndEnumEndClass
    ' Extends the standard button control and performs' custom drawing with a GradientFill background.PublicClass GradientFilledButton
        Inherits Control
        Private components As System.ComponentModel.IContainer = NothingPublicSubNew()
            components = New System.ComponentModel.Container()
            Me.Font = New Font(Me.Font.Name, Me.Font.Size, FontStyle.Bold)
    
        EndSub
        ' Controls the direction in which the button is filled.PublicProperty FillDirection() As GradientFill.FillDirection
            GetReturn fillDirectionValue
            EndGetSet(ByVal value As GradientFill.FillDirection)
                fillDirectionValue = value
                Invalidate()
            EndSetEndPropertyPrivate fillDirectionValue As GradientFill.FillDirection
    
        ' The start color for the GradientFill. This is the color    ' at the left or top of the control depeneding on the value    ' of the FillDirection property.PublicProperty StartColor() As Color
            GetReturn startColorValue
            EndGetSet(ByVal value As Color)
                startColorValue = value
                Invalidate()
            EndSetEndPropertyPrivate startColorValue As Color = Color.Red
    
        ' The end color for the GradientFill. This is the color    ' at the right or bottom of the control depending on the value    ' of the FillDirection propertyPublicProperty EndColor() As Color
            GetReturn endColorValue
            EndGetSet(ByVal value As Color)
                endColorValue = value
                Invalidate()
            EndSetEndPropertyPrivate endColorValue As Color = Color.Blue
    
        ' This is the offset from the left or top edge    '  of the button to start the gradient fill.PublicProperty StartOffset() AsIntegerGetReturn startOffsetValue
            EndGetSet(ByVal value AsInteger)
                startOffsetValue = value
                Invalidate()
            EndSetEndPropertyPrivate startOffsetValue AsInteger
        ' This is the offset from the right or bottom edge    '  of the button to end the gradient fill.PublicProperty EndOffset() AsIntegerGetReturn endOffsetValue
            EndGetSet(ByVal value AsInteger)
                endOffsetValue = value
                Invalidate()
            EndSetEndPropertyPrivate endOffsetValue AsInteger
        ' Used to double-buffer our drawing to avoid flicker    ' between painting the background, border, focus-rect    ' and the text of the control.PrivateProperty DoubleBufferImage() As Bitmap
            GetIf bmDoubleBuffer IsNothingThen
                    bmDoubleBuffer = New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height)
                EndIfReturn bmDoubleBuffer
            EndGetSet(ByVal value As Bitmap)
                IfNot (bmDoubleBuffer IsNothing) Then
                    bmDoubleBuffer.Dispose()
                EndIf
                bmDoubleBuffer = value
            EndSetEndPropertyPrivate bmDoubleBuffer As Bitmap
    
    
        ' Called when the control is resized. When that happens,    ' recreate the bitmap used for double-buffering.ProtectedOverridesSub OnResize(ByVal e As EventArgs)
            DoubleBufferImage = New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height)
            MyBase.OnResize(e)
        EndSub
    
        ' Called when the control gets focus. Need to repaint    ' the control to ensure the focus rectangle is drawn correctly.ProtectedOverridesSub OnGotFocus(ByVal e As EventArgs)
            MyBase.OnGotFocus(e)
            Me.Invalidate()
        EndSub
        ' Called when the control loses focus. Need to repaint    ' the control to ensure the focus rectangle is removed.ProtectedOverridesSub OnLostFocus(ByVal e As EventArgs)
            MyBase.OnLostFocus(e)
            Me.Invalidate()
        EndSubProtectedOverridesSub OnMouseMove(ByVal e As MouseEventArgs)
            IfMe.Capture ThenDim coord AsNew Point(e.X, e.Y)
                IfMe.ClientRectangle.Contains(coord) <> Me.ClientRectangle.Contains(lastCursorCoordinates) Then
                    DrawButton(Me.ClientRectangle.Contains(coord))
                EndIf
                lastCursorCoordinates = coord
            EndIfMyBase.OnMouseMove(e)
    
        EndSub
        ' The coordinates of the cursor the last time    ' there was a MouseUp or MouseDown message.Private lastCursorCoordinates As Point
    
    
        ProtectedOverridesSub OnMouseDown(ByVal e As MouseEventArgs)
            If e.Button = System.Windows.Forms.MouseButtons.Left Then            ' Start capturing the mouse inputMe.Capture = True            ' Get the focus because button is clicked.Me.Focus()
    
                ' draw the button
                DrawButton(True)
            EndIfMyBase.OnMouseDown(e)
    
        EndSubProtectedOverridesSub OnMouseUp(ByVal e As MouseEventArgs)
            Me.Capture = False
            DrawButton(False)
            MyBase.OnMouseUp(e)
        EndSubPrivate bGotKeyDown AsBoolean = FalseProtectedOverridesSub OnKeyDown(ByVal e As KeyEventArgs)
            bGotKeyDown = TrueSelectCase e.KeyCode
                Case Keys.Space, Keys.Enter
                    DrawButton(True)
                Case Keys.Up, Keys.Left
                    Me.Parent.SelectNextControl(Me, False, False, True, True)
                Case Keys.Down, Keys.Right
                    Me.Parent.SelectNextControl(Me, True, False, True, True)
                CaseElse
                    bGotKeyDown = FalseMyBase.OnKeyDown(e)
            EndSelectEndSubProtectedOverridesSub OnKeyUp(ByVal e As KeyEventArgs)
            SelectCase e.KeyCode
                Case Keys.Space, Keys.Enter
                    If bGotKeyDown Then
                        DrawButton(False)
                        OnClick(EventArgs.Empty)
                        bGotKeyDown = FalseEndIfCaseElseMyBase.OnKeyUp(e)
            EndSelectEndSub
    
        ' Override this method with no code to avoid flicker.ProtectedOverridesSub OnPaintBackground(ByVal e As PaintEventArgs)
    
        EndSubProtectedOverridesSub OnPaint(ByVal e As PaintEventArgs)
            DrawButton(e.Graphics, Me.Capture AndAlsoMe.ClientRectangle.Contains(lastCursorCoordinates))
    
        EndSub
    
        ' Gets a Graphics object for the provided window handle    '  and then calls DrawButton(Graphics, bool).    ' If pressed is true, the button is drawn    ' in the depressed state.OverloadsSub DrawButton(ByVal pressed AsBoolean)
            Dim gr As Graphics = Me.CreateGraphics()
            DrawButton(gr, pressed)
            gr.Dispose()
        EndSub
    
        ' Draws the button on the specified Grapics    ' in the specified state.    '    ' Parameters:    '  gr - The Graphics object on which to draw the button.    '  pressed - If true, the button is drawn in the depressed state.OverloadsSub DrawButton(ByVal gr As Graphics, ByVal pressed AsBoolean)
            ' Get a Graphics object from the background image.Dim gr2 As Graphics = Graphics.FromImage(DoubleBufferImage)
    
            ' Fill solid up until where the gradient fill starts.If startOffsetValue > 0 ThenIf fillDirectionValue = GradientFill.FillDirection.LeftToRight ThenIf pressed Then
                        gr2.FillRectangle(New SolidBrush(EndColor), 0, 0, startOffsetValue, Height)
                    Else
                        gr2.FillRectangle(New SolidBrush(StartColor), 0, 0, startOffsetValue, Height)
                    EndIfElseIf pressed Then
                        gr2.FillRectangle(New SolidBrush(EndColor), 0, 0, Width, startOffsetValue)
                    Else
                        gr2.FillRectangle(New SolidBrush(StartColor), 0, 0, Width, startOffsetValue)
                    EndIfEndIfEndIf
            ' Draw the gradient fill.Dim rc As Rectangle = Me.ClientRectangle
            If fillDirectionValue = GradientFill.FillDirection.LeftToRight Then
                rc.X = startOffsetValue
                rc.Width = rc.Width - startOffsetValue - endOffsetValue
            Else
                rc.Y = startOffsetValue
                rc.Height = rc.Height - startOffsetValue - endOffsetValue
            EndIfIf pressed Then
                GradientFill.Fill(gr2, rc, endColorValue, startColorValue, fillDirectionValue)
            Else
                GradientFill.Fill(gr2, rc, startColorValue, endColorValue, fillDirectionValue)
            EndIf
            ' Fill solid from the end of the gradient fill        ' to the edge of the button.If endOffsetValue > 0 ThenIf fillDirectionValue = GradientFill.FillDirection.LeftToRight ThenIf pressed Then
                        gr2.FillRectangle(New SolidBrush(StartColor), rc.X + rc.Width, 0, endOffsetValue, Height)
                    Else
                        gr2.FillRectangle(New SolidBrush(EndColor), rc.X + rc.Width, 0, endOffsetValue, Height)
                    EndIfElseIf pressed Then
                        gr2.FillRectangle(New SolidBrush(StartColor), 0, rc.Y + rc.Height, Width, endOffsetValue)
                    Else
                        gr2.FillRectangle(New SolidBrush(StartColor), 0, rc.Y + rc.Height, Width, endOffsetValue)
                    EndIfEndIfEndIf
            ' Draw the text.Dim sf AsNew StringFormat()
            sf.Alignment = StringAlignment.Center
            sf.LineAlignment = StringAlignment.Center
            gr2.DrawString(Me.Text, Me.Font, New SolidBrush(Me.ForeColor), Me.ClientRectangle, sf)
    
            ' Draw the border.        ' Need to shrink the width and height by 1 otherwise        ' there will be no border on the right or bottom.
            rc = Me.ClientRectangle
            rc.Width -= 1
            rc.Height -= 1
            Dim pen AsNew Pen(SystemColors.WindowFrame)
    
            gr2.DrawRectangle(pen, rc)
    
            ' Draw from the background image onto the screen.
            gr.DrawImage(DoubleBufferImage, 0, 0)
            gr2.Dispose()
    
        EndSubProtectedOverridesSub Dispose(ByVal disposing AsBoolean)
            If disposing AndAlsoNot (components IsNothing) Then
                components.Dispose()
            EndIfMyBase.Dispose(disposing)
    
        EndSubEndClass
    
                                  public
                                  sealed
                                  class GradientFill
        {
            // This method wraps the PInvoke to GradientFill.// Parmeters://  gr - The Graphics object we are filling//  rc - The rectangle to fill//  startColor - The starting color for the fill//  endColor - The ending color for the fill//  fillDir - The direction to fill//// Returns true if the call to GradientFill succeeded; false// otherwise.publicstaticbool Fill(
                Graphics gr,
                Rectangle rc,
                Color startColor, Color endColor,
                FillDirection fillDir)
            {
    
                // Initialize the data to be used in the call to GradientFill.
                Win32Helper.TRIVERTEX[] tva = new Win32Helper.TRIVERTEX[2];
                tva[0] = new Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor);
                tva[1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor);
                Win32Helper.GRADIENT_RECT[] gra = new Win32Helper.GRADIENT_RECT[] {
            new Win32Helper.GRADIENT_RECT(0, 1)};
    
                // Get the hDC from the Graphics object.
                IntPtr hdc = gr.GetHdc();
    
                // PInvoke to GradientFill.bool b;
    
                b = Win32Helper.GradientFill(
                        hdc,
                        tva,
                        (uint)tva.Length,
                        gra,
                        (uint)gra.Length,
                        (uint)fillDir);
                System.Diagnostics.Debug.Assert(b, string.Format(
                    "GradientFill failed: {0}",
                    System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
    
                // Release the hDC from the Graphics object.
                gr.ReleaseHdc(hdc);
    
                return b;
            }
    
            // The direction to the GradientFill will followpublicenum FillDirection
            {
                //// The fill goes horizontally//
                LeftToRight = Win32Helper.GRADIENT_FILL_RECT_H,
                //// The fill goes vertically//
                TopToBottom = Win32Helper.GRADIENT_FILL_RECT_V
            }
        }
    
        // Extends the standard button control and performs// custom drawing with a GradientFill background.publicclass GradientFilledButton : Control
        {
            private System.ComponentModel.IContainer components = null;
    
            public GradientFilledButton()
            {
                components = new System.ComponentModel.Container();
                this.Font = new Font(this.Font.Name, this.Font.Size, FontStyle.Bold);
            }
    
            // Controls the direction in which the button is filled.public GradientFill.FillDirection FillDirection
            {
                get
                {
                    return fillDirectionValue;
                }
                set
                {
                    fillDirectionValue = value;
                    Invalidate();
                }
            }
            private GradientFill.FillDirection fillDirectionValue;
    
            // The start color for the GradientFill. This is the color// at the left or top of the control depeneding on the value// of the FillDirection property.public Color StartColor
            {
                get { return startColorValue; }
                set
                {
                    startColorValue = value;
                    Invalidate();
                }
            }
            private Color startColorValue = Color.Red;
    
            // The end color for the GradientFill. This is the color// at the right or bottom of the control depending on the value// of the FillDirection propertypublic Color EndColor
            {
                get { return endColorValue; }
                set
                {
                    endColorValue = value;
                    Invalidate();
                }
            }
            private Color endColorValue = Color.Blue;
    
            // This is the offset from the left or top edge//  of the button to start the gradient fill.publicint StartOffset
            {
                get { return startOffsetValue; }
                set
                {
                    startOffsetValue = value;
                    Invalidate();
                }
            }
            privateint startOffsetValue;
    
            // This is the offset from the right or bottom edge//  of the button to end the gradient fill.publicint EndOffset
            {
                get { return endOffsetValue; }
                set
                {
                    endOffsetValue = value;
                    Invalidate();
                }
            }
            privateint endOffsetValue;
    
            // Used to double-buffer our drawing to avoid flicker// between painting the background, border, focus-rect// and the text of the control.private Bitmap DoubleBufferImage
            {
                get
                {
                    if (bmDoubleBuffer == null)
                        bmDoubleBuffer = new Bitmap(
                            this.ClientSize.Width,
                            this.ClientSize.Height);
                    return bmDoubleBuffer;
                }
                set
                {
                    if (bmDoubleBuffer != null)
                        bmDoubleBuffer.Dispose();
                    bmDoubleBuffer = value;
                }
            }
            private Bitmap bmDoubleBuffer;
    
            // Called when the control is resized. When that happens,// recreate the bitmap used for double-buffering.protectedoverridevoid OnResize(EventArgs e)
            {
                DoubleBufferImage = new Bitmap(
                    this.ClientSize.Width,
                    this.ClientSize.Height);
                base.OnResize(e);
            }
    
            // Called when the control gets focus. Need to repaint// the control to ensure the focus rectangle is drawn correctly.protectedoverridevoid OnGotFocus(EventArgs e)
            {
                base.OnGotFocus(e);
                this.Invalidate();
            }
            //// Called when the control loses focus. Need to repaint// the control to ensure the focus rectangle is removed.protectedoverridevoid OnLostFocus(EventArgs e)
            {
                base.OnLostFocus(e);
                this.Invalidate();
            }
    
            protectedoverridevoid OnMouseMove(MouseEventArgs e)
            {
                if (this.Capture)
                {
                    Point coord = new Point(e.X, e.Y);
                    if (this.ClientRectangle.Contains(coord) !=
                        this.ClientRectangle.Contains(lastCursorCoordinates))
                    {
                        DrawButton(this.ClientRectangle.Contains(coord));
                    }
                    lastCursorCoordinates = coord;
                }
                base.OnMouseMove(e);
            }
    
            // The coordinates of the cursor the last time// there was a MouseUp or MouseDown message.
            Point lastCursorCoordinates;
    
            protectedoverridevoid OnMouseDown(MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Left)
                {
                    // Start capturing the mouse inputthis.Capture = true;
                    // Get the focus because button is clicked.this.Focus();
    
                    // draw the button
                    DrawButton(true);
                }
    
                base.OnMouseDown(e);
            }
    
            protectedoverridevoid OnMouseUp(MouseEventArgs e)
            {
                this.Capture = false;
    
                DrawButton(false);
    
                base.OnMouseUp(e);
            }
    
            bool bGotKeyDown = false;
            protectedoverridevoid OnKeyDown(KeyEventArgs e)
            {
                bGotKeyDown = true;
                switch (e.KeyCode)
                {
                    case Keys.Space:
                    case Keys.Enter:
                        DrawButton(true);
                        break;
                    case Keys.Up:
                    case Keys.Left:
                        this.Parent.SelectNextControl(this, false, false, true, true);
                        break;
                    case Keys.Down:
                    case Keys.Right:
                        this.Parent.SelectNextControl(this, true, false, true, true);
                        break;
                    default:
                        bGotKeyDown = false;
                        base.OnKeyDown(e);
                        break;
                }
            }
    
            protectedoverridevoid OnKeyUp(KeyEventArgs e)
            {
                switch (e.KeyCode)
                {
                    case Keys.Space:
                    case Keys.Enter:
                        if (bGotKeyDown)
                        {
                            DrawButton(false);
                            OnClick(EventArgs.Empty);
                            bGotKeyDown = false;
                        }
                        break;
                    default:
                        base.OnKeyUp(e);
                        break;
                }
            }
    
            // Override this method with no code to avoid flicker.protectedoverridevoid OnPaintBackground(PaintEventArgs e)
            {
            }
            protectedoverridevoid OnPaint(PaintEventArgs e)
            {
                DrawButton(e.Graphics, this.Capture &&
                    (this.ClientRectangle.Contains(lastCursorCoordinates)));
            }
    
            //// Gets a Graphics object for the provided window handle//  and then calls DrawButton(Graphics, bool).//// If pressed is true, the button is drawn// in the depressed state.void DrawButton(bool pressed)
            {
                Graphics gr = this.CreateGraphics();
                DrawButton(gr, pressed);
                gr.Dispose();
            }
    
            // Draws the button on the specified Grapics// in the specified state.//// Parameters://  gr - The Graphics object on which to draw the button.//  pressed - If true, the button is drawn in the depressed state.void DrawButton(Graphics gr, bool pressed)
            {
                // Get a Graphics object from the background image.
                Graphics gr2 = Graphics.FromImage(DoubleBufferImage);
    
                // Fill solid up until where the gradient fill starts.if (startOffsetValue > 0)
                {
                    if (fillDirectionValue ==
                        GradientFill.FillDirection.LeftToRight)
                    {
                        gr2.FillRectangle(
                            new SolidBrush(pressed ? EndColor : StartColor),
                            0, 0, startOffsetValue, Height);
                    }
                    else
                    {
                        gr2.FillRectangle(
                            new SolidBrush(pressed ? EndColor : StartColor),
                            0, 0, Width, startOffsetValue);
                    }
                }
    
                // Draw the gradient fill.
                Rectangle rc = this.ClientRectangle;
                if (fillDirectionValue == GradientFill.FillDirection.LeftToRight)
                {
                    rc.X = startOffsetValue;
                    rc.Width = rc.Width - startOffsetValue - endOffsetValue;
                }
                else
                {
                    rc.Y = startOffsetValue;
                    rc.Height = rc.Height - startOffsetValue - endOffsetValue;
                }
                GradientFill.Fill(
                    gr2,
                    rc,
                    pressed ? endColorValue : startColorValue,
                    pressed ? startColorValue : endColorValue,
                    fillDirectionValue);
    
                // Fill solid from the end of the gradient fill// to the edge of the button.if (endOffsetValue > 0)
                {
                    if (fillDirectionValue ==
                        GradientFill.FillDirection.LeftToRight)
                    {
                        gr2.FillRectangle(
                            new SolidBrush(pressed ? StartColor : EndColor),
                            rc.X + rc.Width, 0, endOffsetValue, Height);
                    }
                    else
                    {
                        gr2.FillRectangle(
                            new SolidBrush(pressed ? StartColor : EndColor),
                            0, rc.Y + rc.Height, Width, endOffsetValue);
                    }
                }
    
                // Draw the text.
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                gr2.DrawString(this.Text, this.Font,
                    new SolidBrush(this.ForeColor),
                    this.ClientRectangle, sf);
    
                // Draw the border.// Need to shrink the width and height by 1 otherwise// there will be no border on the right or bottom.
                rc = this.ClientRectangle;
                rc.Width--;
                rc.Height--;
                Pen pen = new Pen(SystemColors.WindowFrame);
    
                gr2.DrawRectangle(pen, rc);
    
                // Draw from the background image onto the screen.
                gr.DrawImage(DoubleBufferImage, 0, 0);
                gr2.Dispose();
            }
    
            protectedoverridevoid Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
        }
    
    
  3. プラットフォームを含む、プロジェクト、Win32Helper クラスを呼び出すし、ネイティブ コードの相互運用性構造体追加します。

                                  Public
                                  NotInheritable
                                  Class Win32Helper
    
        PublicStructure TRIVERTEX
            Public x AsIntegerPublic y AsIntegerPublic Red As System.Int16
            Public Green As System.Int16
            Public Blue As System.Int16
            Public Alpha As System.Int16
    
            PublicSubNew(ByVal x AsInteger, ByVal y AsInteger, ByVal color As Color)
                MyClass.New(x, y, color.R, color.G, color.B, color.A)
            EndSubPublicSubNew(ByVal x AsInteger, ByVal y AsInteger, ByVal red As System.Int16, ByVal green As System.Int16, ByVal blue As System.Int16, ByVal alpha As System.Int16)
                Me.x = x
                Me.y = y
    
                Me.Red = CInt(red << 8)
                Me.Green = CInt(green << 8)
                Me.Blue = CInt(blue << 8)
                Me.Alpha = CInt(alpha << 8)
            EndSubEndStructurePublicStructure GRADIENT_RECT
            Public UpperLeft As System.Int32
            Public LowerRight As System.Int32
    
            PublicSubNew(ByVal ul As System.Int32, ByVal lr As System.Int32)
                Me.UpperLeft = ul
                Me.LowerRight = lr
            EndSubEndStructurePublicDeclareFunction GradientFill Lib"coredll.dll"Alias"GradientFill" (ByVal hdc As IntPtr, _
         ByVal pVertex() As TRIVERTEX, ByVal dwNumVertex AsInteger, _
         ByVal pMesh() As GRADIENT_RECT, ByVal dwNumMesh AsInteger, _
         ByVal dwMode AsInteger) AsBooleanPublicConst GRADIENT_FILL_RECT_H AsInteger = &H0
        PublicConst GRADIENT_FILL_RECT_V AsInteger = &H1
    EndClass
    
                                  public
                                  sealed
                                  class Win32Helper
    {
        publicstruct TRIVERTEX
        {
            publicint x;
            publicint y;
            publicushort Red;
            publicushort Green;
            publicushort Blue;
            publicushort Alpha;
            public TRIVERTEX(int x, int y, Color color)
                : this(x, y, color.R, color.G, color.B, color.A)
            {
            }
            public TRIVERTEX(
                int x, int y,
                ushort red, ushort green, ushort blue,
                ushort alpha)
            {
                this.x = x;
                this.y = y;
                this.Red = (ushort)(red << 8);
                this.Green = (ushort)(green << 8);
                this.Blue = (ushort)(blue << 8);
                this.Alpha = (ushort)(alpha << 8);
            }
        }
        publicstruct GRADIENT_RECT
        {
            publicuint UpperLeft;
            publicuint LowerRight;
            public GRADIENT_RECT(uint ul, uint lr)
            {
                this.UpperLeft = ul;
                this.LowerRight = lr;
            }
        }
    
    
        [DllImport("coredll.dll", SetLastError = true, EntryPoint = "GradientFill")]
        publicexternstaticbool GradientFill(
            IntPtr hdc,
            TRIVERTEX[] pVertex,
            uint dwNumVertex,
            GRADIENT_RECT[] pMesh,
            uint dwNumMesh,
            uint dwMode);
    
        publicconstint GRADIENT_FILL_RECT_H = 0x00000000;
        publicconstint GRADIENT_FILL_RECT_V = 0x00000001;
    
    }
    
  4. 種類 gfButtonGradientFilledButton をという名前のフォーム変数を宣言します。

                                  Private gfButton As GradientFilledButton
    
    
                                  private GradientFilledButton gfButton;
    
  5. Form1 クラスのコンストラクターに、グラデーションの塗りつぶされたボタン カスタム コントロールの初期化、次のコードを追加します。 このコードは、InitializeComponent メソッドを呼び出す従ってください。 開始および終了色のグラデーションの塗りつぶしと TopToBottom または LeftToRight 塗りつぶし方向を指定できます。

    InitializeComponent()
    Me.gfButton = New GradientFilledButton()
    Me.gfButton.Location = New System.Drawing.Point(71, 24)
    Me.gfButton.Name = "gfButton"Me.gfButton.Size = New System.Drawing.Size(100, 23)
    Me.gfButton.TabIndex = 1
    Me.gfButton.Text = "Button Test"AddHandlerMe.gfButton.Click, AddressOfMe.gfButton_Click
    
    ' Select desired start color, end color, and fill direction.Me.gfButton.StartColor = System.Drawing.Color.SlateBlue
    Me.gfButton.EndColor = System.Drawing.Color.LightCyan
    gfButton.FillDirection = GradientFill.FillDirection.LeftToRight
    
    Me.Controls.Add(gfButton)
    
    InitializeComponent();
    this.gfButton = new GradientFilledButton();
    this.gfButton.Location = new System.Drawing.Point(71, 24);
    this.gfButton.Name = "gfButton";
    this.gfButton.Size = new System.Drawing.Size(100, 23);
    this.gfButton.TabIndex = 1;
    this.gfButton.Text = "Button Test";
    this.gfButton.Click += new System.EventHandler(this.gfButton_Click);
    
    // Select desired start color, end color, and fill direction.this.gfButton.StartColor = System.Drawing.Color.SlateBlue;
    this.gfButton.EndColor = System.Drawing.Color.LightCyan;
    gfButton.FillDirection = GradientFill.FillDirection.LeftToRight;
    
    this.Controls.Add(gfButton);
    
  6. イベント処理フォームにボタンの Click イベント コードを追加します。

                                  Private
                                  Sub gfButton_Click(ByVal sender AsObject, ByVal e As System.EventArgs) 
        Dim control As Control = sender
        System.Diagnostics.Debug.Assert( Not (control IsNothing))
        MessageBox.Show("Clicked", "Click event handler")
    EndSub
    
                                  void gfButton_Click(object sender, System.EventArgs e)
    {
        Control control = sender as Control;
        System.Diagnostics.Debug.Assert(control != null);
        MessageBox.Show("Clicked", "Click event handler");
    }
    
  7. グラデーションの塗りつぶしパターンを持つ、フォームの背景を描画するには、OnPaint メソッド オーバーライドします。 このコードは、GradientFill クラスは、 GradientFilledButton クラスではないで使用します。

                                  ' Paints the background of the form with a GradientFill pattern.
                                  Protected
                                  Overrides
                                  Sub OnPaintBackground(ByVal e As PaintEventArgs) 
        ' On Windows Mobile Pocket PC 2003, the call to GradientFill    ' fails with GetLastError() returning 87 (ERROR_INVALID_PARAMETER)    ' when e.Graphics is used.    ' Instead, fill into a bitmap and then draw that onto e.Graphics.Dim bm AsNew Bitmap(Width, Height)
        Dim gr As Graphics = System.Drawing.Graphics.FromImage(bm)
    
        GradientFill.Fill(gr, Me.ClientRectangle, Color.LightCyan, Color.SlateBlue, GradientFill.FillDirection.TopToBottom)
        e.Graphics.DrawImage(bm, 0, 0)
        gr.Dispose()
        bm.Dispose()
    
    EndSub
    
                                  // Paints the background of the form with a GradientFill pattern.
                                  protected
                                  override
                                  void OnPaintBackground(PaintEventArgs e)
    {
        // On Windows Mobile Pocket PC 2003, the call to GradientFill// fails with GetLastError() returning 87 (ERROR_INVALID_PARAMETER)// when e.Graphics is used.// Instead, fill into a bitmap and then draw that onto e.Graphics.
        Bitmap bm = new Bitmap(Width, Height);
        Graphics gr = System.Drawing.Graphics.FromImage(bm);
    
        GradientFill.Fill(
            gr,
            this.ClientRectangle,
            Color.LightCyan, Color.SlateBlue,
            GradientFill.FillDirection.TopToBottom);
        e.Graphics.DrawImage(bm, 0, 0);
        gr.Dispose();
        bm.Dispose();
    }
    
  8. ビルドしてアプリケーションを展開します。

参照

概念

.NET コンパクトなフレームワーク方法を説明したトピックの検索

その他の技術情報

グラフィックスと、.NET での描画の最適化フレームワーク