VisualStyleRenderer 類別

定義

提供繪製和取得有關 VisualStyleElement 之資訊的方法。 此類別無法獲得繼承。

public ref class VisualStyleRenderer sealed
public sealed class VisualStyleRenderer
type VisualStyleRenderer = class
Public NotInheritable Class VisualStyleRenderer
繼承
VisualStyleRenderer

範例

下列程式碼範例會 VisualStyleRenderer 使用 類別來實作自訂控制項,以模擬視窗的某些基本 UI,包括使用標題列拖曳、使用調整大小控點調整大小,以及關閉。 這個範例會使用數 VisualStyleElement 個物件來代表視窗的標準部分,包括 、 VisualStyleElement.Window.CloseButtonVisualStyleElement.Status.Gripper 類別所 VisualStyleElement.Window.Caption 公開的專案。

#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
using namespace System::Collections::Generic;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::VisualStyles;

namespace VisualStyleRendererSample
{

    public ref class WindowSimulation : public Control
    {
    private:
        Dictionary<String^, VisualStyleElement^>^ windowElements;
        Dictionary<String^, Rectangle>^ elementRectangles;
        VisualStyleRenderer^ renderer;
        Point closeButtonOffset;
        System::Drawing::Size gripperSize;
        System::Drawing::Size closeButtonSize;
        bool isResizing;
        bool isMoving;
        bool isClosing;
        int captionHeight;
        int frameThickness;
        int statusHeight;
        Point originalClick;
        Point resizeOffset;

    public:
        WindowSimulation() : Control()
        {
            statusHeight = 22;
            windowElements = gcnew Dictionary<String^, VisualStyleElement^>();
            elementRectangles = gcnew Dictionary<String^, Rectangle>();
            this->Location = Point(50, 50);
            this->Size = System::Drawing::Size(350, 300);
            this->BackColor = Color::Azure;
            this->DoubleBuffered = true;
            this->MinimumSize = System::Drawing::Size(300, 200);
            this->Font = SystemFonts::CaptionFont;
            this->Text = "Simulated Window";

            // Insert the VisualStyleElement objects into the Dictionary.
            windowElements->Add("windowCaption",
                VisualStyleElement::Window::Caption::Active);
            windowElements->Add("windowBottom",
                VisualStyleElement::Window::FrameBottom::Active);
            windowElements->Add("windowLeft",
                VisualStyleElement::Window::FrameLeft::Active);
            windowElements->Add("windowRight",
                VisualStyleElement::Window::FrameRight::Active);
            windowElements->Add("windowClose",
                VisualStyleElement::Window::CloseButton::Normal);
            windowElements->Add("statusBar",
                VisualStyleElement::Status::Bar::Normal);
            windowElements->Add("statusGripper",
                VisualStyleElement::Status::Gripper::Normal);

            // Get the sizes and location offsets for the window parts
            // as specified by the visual style, and then use this
            // information to calcualate the rectangles for each part.
            GetPartDetails();
            CalculateRectangles();

            this->MouseDown +=
                gcnew MouseEventHandler(this,
                    &WindowSimulation::ImitationWindow_MouseDown);
            this->MouseUp +=
                gcnew MouseEventHandler(this,
                    &WindowSimulation::ImitationWindow_MouseUp);
            this->MouseMove +=
                gcnew MouseEventHandler(this,
                    &WindowSimulation::ImitationWindow_MouseMove);
        }

        // Get the sizes and offsets for the window parts as specified
        // by the visual style.
    private:
        void GetPartDetails()
        {
            // Do nothing further if visual styles are not enabled.
            if (!Application::RenderWithVisualStyles)
            {
                return;
            }

            Graphics^ g = this->CreateGraphics();

            // Get the size and offset of the close button.
            if (SetRenderer(windowElements["windowClose"]))
            {
                closeButtonSize =
                    renderer->GetPartSize(g, ThemeSizeType::True);
                closeButtonOffset =
                    renderer->GetPoint(PointProperty::Offset);
            }

            // Get the height of the window caption.
            if (SetRenderer(windowElements["windowCaption"]))
            {
                captionHeight = renderer->GetPartSize(g,
                    ThemeSizeType::True).Height;
            }

            // Get the thickness of the left, bottom,
            // and right window frame.
            if (SetRenderer(windowElements["windowLeft"]))
            {
                frameThickness = renderer->GetPartSize(g,
                    ThemeSizeType::True).Width;
            }

            // Get the size of the resizing gripper.
            if (SetRenderer(windowElements["statusGripper"]))
            {
                gripperSize = renderer->GetPartSize(g,
                    ThemeSizeType::True);
            }

        }

        // Use the part metrics to determine the current size
        // of the rectangles for all of the window parts.
    private:
        void CalculateRectangles()
        {
            int heightMinusFrame =
                ClientRectangle.Height - frameThickness;

            // Calculate the window frame rectangles and add them
            // to the Dictionary of rectangles.
            elementRectangles["windowCaption"] = Rectangle(0, 0,
                ClientRectangle.Width, captionHeight);
            elementRectangles["windowBottom"] = Rectangle(0,
                heightMinusFrame, ClientRectangle.Width, frameThickness);
            elementRectangles["windowLeft"] = Rectangle(0, captionHeight,
                frameThickness, heightMinusFrame - captionHeight);
            elementRectangles["windowRight"] = Rectangle(
                ClientRectangle.Width - frameThickness, captionHeight,
                frameThickness, heightMinusFrame - captionHeight);

            // Calculate the window button rectangle and add it
            // to the Dictionary of rectangles.
            elementRectangles["windowClose"] =
                Rectangle(ClientRectangle.Right +
                    closeButtonOffset.X - closeButtonSize.Width - frameThickness, closeButtonOffset.Y,
                    closeButtonSize.Width, closeButtonSize.Height);

            // Calculate the status bar rectangles and add them
            // to the Dictionary of rectangles.
            elementRectangles["statusBar"] =
                Rectangle(frameThickness,
                    heightMinusFrame - statusHeight,
                    ClientRectangle.Width - (2 * frameThickness),
                    statusHeight);
            elementRectangles["statusGripper"] =
                Rectangle(ClientRectangle.Right -
                gripperSize.Width - frameThickness,
                heightMinusFrame - gripperSize.Height,
                gripperSize.Width, gripperSize.Height);
        }

    protected:
        virtual void OnPaint(PaintEventArgs^ e) override
        {
            __super::OnPaint(e);

            // Ensure that visual styles are supported.
            if (!Application::RenderWithVisualStyles)
            {
                this->Text = "Visual styles are not enabled.";
                TextRenderer::DrawText(e->Graphics, this->Text,
                    this->Font, this->Location, this->ForeColor);
                return;
            }

            // Set the clip region to define the curved corners
            // of the caption.
            SetClipRegion();

            // Draw each part of the window.
            for each(KeyValuePair<String^, VisualStyleElement^>^ entry
                in windowElements)
            {
                if (SetRenderer(entry->Value))
                {
                    renderer->DrawBackground(e->Graphics,
                        elementRectangles[entry->Key]);
                }
            }

            // Draw the caption text.
            TextRenderer::DrawText(e->Graphics, this->Text, this->Font,
                elementRectangles["windowCaption"], Color::White,
                TextFormatFlags::VerticalCenter |
                TextFormatFlags::HorizontalCenter);
        }
private:
        // Initiate dragging, resizing, or closing the imitation window.
        void ImitationWindow_MouseDown(Object^ sender, MouseEventArgs^ e)
        {
            // The user clicked the close button.
            if (elementRectangles["windowClose"].Contains(e->Location))
            {
                windowElements["windowClose"] =
                    VisualStyleElement::Window::CloseButton::Pressed;
                isClosing = true;
            }

            // The user clicked the status grip.
            else if (elementRectangles["statusGripper"].Contains(e->Location))
            {
                isResizing = true;
                this->Cursor = Cursors::SizeNWSE;
                resizeOffset.X = this->Right - this->Left - e->X;
                resizeOffset.Y = this->Bottom - this->Top - e->Y;
            }

            // The user clicked the window caption.
            else if (elementRectangles["windowCaption"].Contains(e->Location))
            {
                isMoving = true;
                originalClick.X = e->X;
                originalClick.Y = e->Y;
            }

            Invalidate();
        }

        // Stop any current resizing or moving actions.
        void ImitationWindow_MouseUp(Object^ sender, MouseEventArgs^ e)
        {
            // Stop moving the location of the window rectangles.
            if (isMoving)
            {
                isMoving = false;
            }

            // Change the cursor back to the default if the user
            // stops resizing.
            else if (isResizing)
            {
                isResizing = false;
            }

            // Close the application if the user clicks the
            // close button.
            else if (elementRectangles["windowClose"].Contains(e->Location) 
                && isClosing)
            {
                Application::Exit();
            }
        }

        // Handle resizing or moving actions.
        void ImitationWindow_MouseMove(Object^ sender,
            MouseEventArgs^ e)
        {
            // The left mouse button is down.
            if ((::MouseButtons::Left & e->Button) == ::MouseButtons::Left)
            {
                // Calculate the new control size if the user is
                // dragging the resizing grip.
                if (isResizing)
                {
                    this->Width = e->X + resizeOffset.X;
                    this->Height = e->Y + resizeOffset.Y;
                    CalculateRectangles();
                }

                // Calculate the new location of the control if the
                // user is dragging the window caption.
                else if (isMoving)
                {
                    int XChange = this->Location.X + (e->X - originalClick.X);
                    int YChange = this->Location.Y + (e->Y - originalClick.Y);
                    this->Location = Point(XChange, YChange);
                }

                // Cancel the closing action if the user clicked
                // and held down on the close button, and has dragged
                // the pointer outside the button.
                else if (!elementRectangles["windowClose"].Contains(
                    e->Location) && isClosing)
                {
                    isClosing = false;
                    windowElements["windowClose"] =
                        VisualStyleElement::Window::CloseButton::Normal;
                }
            }

            // The left mouse button is not down.
            else
            {
                // Paint the close button hot if the cursor is on it.
                Rectangle^ closeRectangle =
                    elementRectangles["windowClose"];
                if (closeRectangle->Contains(e->Location))
                {
                    windowElements["windowClose"] =
                        VisualStyleElement::Window::CloseButton::Hot;
                }
                else
                {
                    windowElements["windowClose"] =
                        VisualStyleElement::Window::CloseButton::Normal;
                }


                // Use a resizing cursor if the cursor is on the
                // status grip.
                Rectangle^ gripRectangle = elementRectangles["statusGripper"];
                if (gripRectangle->Contains(e->Location))
                {
                    this->Cursor = Cursors::SizeNWSE;
                }
                else
                {
                    this->Cursor = Cursors::Default;
                }
            }

            Invalidate();
        }

        // Calculate and set the clipping region for the control
        // so that the corners of the title bar are rounded.
    private:
        void SetClipRegion()
        {
            if (!Application::RenderWithVisualStyles)
            {
                return;
            }

            Graphics^ g = this->CreateGraphics();
            // Get the current region for the window caption.
            if (SetRenderer(windowElements["windowCaption"]))
            {
                System::Drawing::Region^ clipRegion =
                    renderer->GetBackgroundRegion(g,
                    elementRectangles["windowCaption"]);

                // Get the client rectangle, but exclude the region
                // of the window caption.
                int height = (int)clipRegion->GetBounds(g).Height;
                System::Drawing::Rectangle nonCaptionRect = Rectangle(
                    ClientRectangle.X, ClientRectangle.Y + height,
                    ClientRectangle.Width, ClientRectangle.Height - height);

                // Add the rectangle to the caption region, and
                // make this region the form's clipping region.
                clipRegion->Union(nonCaptionRect);
                this->Region = clipRegion;
            }

        }

        // Set the VisualStyleRenderer to a new element.
    private:
        bool SetRenderer(VisualStyleElement^ element)
        {
            if (!VisualStyleRenderer::IsElementDefined(element))
            {
                return false;
            }

            if (renderer == nullptr)
            {
                renderer = gcnew VisualStyleRenderer(element);
            }
            else
            {
                renderer->SetParameters(element);
            }

            return true;
        }
    };

    public ref class Form1 : public Form
    {
    public:
        Form1() : Form()
        {
            this->Size = System::Drawing::Size(800, 600);
            this->Location = Point(20, 20);
            this->BackColor = Color::DarkGray;
            WindowSimulation^ ws = gcnew WindowSimulation();
            Controls->Add(ws);
        }

    };
}

[STAThread]
int main()
{
    Application::EnableVisualStyles();
    Application::Run(gcnew VisualStyleRendererSample::Form1());
}
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace VisualStyleRendererSample
{
    class Form1 : Form
    {
        public Form1()
            : base()
        {
            this.Size = new Size(800, 600);
            this.Location = new Point(20, 20);
            this.BackColor = Color.DarkGray;
            WindowSimulation Window1 = new WindowSimulation();
            Controls.Add(Window1);
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }

    public class WindowSimulation : Control
    {
        private Dictionary<string, VisualStyleElement> windowElements =
            new Dictionary<string, VisualStyleElement>();
        private Dictionary<string, Rectangle> elementRectangles =
            new Dictionary<string, Rectangle>();
        private VisualStyleRenderer renderer = null;

        private Point closeButtonOffset;
        private Size gripperSize;
        private Size closeButtonSize;
        private bool isResizing = false;
        private bool isMoving = false;
        private bool isClosing = false;
        private int captionHeight;
        private int frameThickness;
        private int statusHeight = 22;
        private Point originalClick = new Point();
        private Point resizeOffset = new Point();

        public WindowSimulation()
            : base()
        {
            this.Location = new Point(50, 50);
            this.Size = new Size(350, 300);
            this.BackColor = Color.Azure;
            this.DoubleBuffered = true;
            this.MinimumSize = new Size(300, 200);
            this.Font = SystemFonts.CaptionFont;
            this.Text = "Simulated Window";

            // Insert the VisualStyleElement objects into the Dictionary.
            windowElements.Add("windowCaption",
                VisualStyleElement.Window.Caption.Active);
            windowElements.Add("windowBottom",
                VisualStyleElement.Window.FrameBottom.Active);
            windowElements.Add("windowLeft",
                VisualStyleElement.Window.FrameLeft.Active);
            windowElements.Add("windowRight",
                VisualStyleElement.Window.FrameRight.Active);
            windowElements.Add("windowClose",
                VisualStyleElement.Window.CloseButton.Normal);
            windowElements.Add("statusBar",
                VisualStyleElement.Status.Bar.Normal);
            windowElements.Add("statusGripper",
                VisualStyleElement.Status.Gripper.Normal);

            // Get the sizes and location offsets for the window parts  
            // as specified by the visual style, and then use this 
            // information to calcualate the rectangles for each part.
            GetPartDetails();
            CalculateRectangles();

            this.MouseDown +=
                new MouseEventHandler(ImitationWindow_MouseDown);
            this.MouseUp +=
                new MouseEventHandler(ImitationWindow_MouseUp);
            this.MouseMove +=
                new MouseEventHandler(ImitationWindow_MouseMove);
        }

        // Get the sizes and offsets for the window parts as specified  
        // by the visual style.
        private void GetPartDetails()
        {
            // Do nothing further if visual styles are not enabled.
            if (!Application.RenderWithVisualStyles)
            {
                return;
            }

            using (Graphics g = this.CreateGraphics())
            {
                // Get the size and offset of the close button.
                if (SetRenderer(windowElements["windowClose"]))
                {
                    closeButtonSize =
                        renderer.GetPartSize(g, ThemeSizeType.True);
                    closeButtonOffset =
                        renderer.GetPoint(PointProperty.Offset);
                }

                // Get the height of the window caption.
                if (SetRenderer(windowElements["windowCaption"]))
                {
                    captionHeight = renderer.GetPartSize(g,
                        ThemeSizeType.True).Height;
                }

                // Get the thickness of the left, bottom, 
                // and right window frame.
                if (SetRenderer(windowElements["windowLeft"]))
                {
                    frameThickness = renderer.GetPartSize(g,
                        ThemeSizeType.True).Width;
                }

                // Get the size of the resizing gripper.
                if (SetRenderer(windowElements["statusGripper"]))
                {
                    gripperSize = renderer.GetPartSize(g,
                        ThemeSizeType.True);
                }
            }
        }

        // Use the part metrics to determine the current size 
        // of the rectangles for all of the window parts.
        private void CalculateRectangles()
        {
            int heightMinusFrame =
                ClientRectangle.Height - frameThickness;

            // Calculate the window frame rectangles and add them
            // to the Dictionary of rectangles.
            elementRectangles["windowCaption"] =
                new Rectangle(0, 0,
                ClientRectangle.Width, captionHeight);
            elementRectangles["windowBottom"] =
                new Rectangle(0, heightMinusFrame,
                ClientRectangle.Width, frameThickness);
            elementRectangles["windowLeft"] =
                new Rectangle(0, captionHeight, frameThickness,
                heightMinusFrame - captionHeight);
            elementRectangles["windowRight"] =
                new Rectangle(ClientRectangle.Width - frameThickness,
                captionHeight, frameThickness,
                heightMinusFrame - captionHeight);

            // Calculate the window button rectangle and add it
            // to the Dictionary of rectangles.
            elementRectangles["windowClose"] =
                new Rectangle(ClientRectangle.Right +
                closeButtonOffset.X - closeButtonSize.Width - frameThickness, closeButtonOffset.Y,
                closeButtonSize.Width, closeButtonSize.Height);

            // Calculate the status bar rectangles and add them
            // to the Dictionary of rectangles.
            elementRectangles["statusBar"] =
                new Rectangle(frameThickness,
                heightMinusFrame - statusHeight,
                ClientRectangle.Width - (2 * frameThickness),
                statusHeight);
            elementRectangles["statusGripper"] =
                new Rectangle(ClientRectangle.Right -
                gripperSize.Width - frameThickness,
                heightMinusFrame - gripperSize.Height,
                gripperSize.Width, gripperSize.Height);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // Ensure that visual styles are supported.
            if (!Application.RenderWithVisualStyles)
            {
                this.Text = "Visual styles are not enabled.";
                TextRenderer.DrawText(e.Graphics, this.Text,
                    this.Font, this.Location, this.ForeColor);
                return;
            }

            // Set the clip region to define the curved corners 
            // of the caption.
            SetClipRegion();

            // Draw each part of the window.
            foreach (KeyValuePair<string, VisualStyleElement> entry
                in windowElements)
            {
                if (SetRenderer(entry.Value))
                {
                    renderer.DrawBackground(e.Graphics,
                        elementRectangles[entry.Key]);
                }
            }

            // Draw the caption text.
            TextRenderer.DrawText(e.Graphics, this.Text, this.Font,
                elementRectangles["windowCaption"], Color.White,
                TextFormatFlags.VerticalCenter |
                TextFormatFlags.HorizontalCenter);
        }

        // Initiate dragging, resizing, or closing the imitation window.
        void ImitationWindow_MouseDown(object sender, MouseEventArgs e)
        {
            // The user clicked the close button.
            if (elementRectangles["windowClose"].Contains(e.Location))
            {
                windowElements["windowClose"] =
                    VisualStyleElement.Window.CloseButton.Pressed;
                isClosing = true;
            }

            // The user clicked the status grip.
            else if (elementRectangles["statusGripper"].
                Contains(e.Location))
            {
                isResizing = true;
                this.Cursor = Cursors.SizeNWSE;
                resizeOffset.X = this.Right - this.Left - e.X;
                resizeOffset.Y = this.Bottom - this.Top - e.Y;
            }

            // The user clicked the window caption.
            else if (elementRectangles["windowCaption"].
                Contains(e.Location))
            {
                isMoving = true;
                originalClick.X = e.X;
                originalClick.Y = e.Y;
            }

            Invalidate();
        }

        // Stop any current resizing or moving actions.
        void ImitationWindow_MouseUp(object sender, MouseEventArgs e)
        {
            // Stop moving the location of the window rectangles.
            if (isMoving)
            {
                isMoving = false;
            }

            // Change the cursor back to the default if the user 
            // stops resizing.
            else if (isResizing)
            {
                isResizing = false;
            }

            // Close the application if the user clicks the 
            // close button.
            else if (elementRectangles["windowClose"].
                Contains(e.Location) && isClosing)
            {
                Application.Exit();
            }
        }

        // Handle resizing or moving actions.
        void ImitationWindow_MouseMove(object sender,
            MouseEventArgs e)
        {
            // The left mouse button is down.
            if ((MouseButtons.Left & e.Button) == MouseButtons.Left)
            {
                // Calculate the new control size if the user is 
                // dragging the resizing grip.
                if (isResizing)
                {
                    this.Width = e.X + resizeOffset.X;
                    this.Height = e.Y + resizeOffset.Y;
                    CalculateRectangles();
                }

                // Calculate the new location of the control if the  
                // user is dragging the window caption.
                else if (isMoving)
                {
                    int XChange = this.Location.X +
                        (e.X - originalClick.X);
                    int YChange = this.Location.Y +
                        (e.Y - originalClick.Y);
                    this.Location = new Point(XChange, YChange);
                }

                // Cancel the closing action if the user clicked  
                // and held down on the close button, and has dragged   
                // the pointer outside the button.
                else if (!elementRectangles["windowClose"].
                    Contains(e.Location) && isClosing)
                {
                    isClosing = false;
                    windowElements["windowClose"] =
                        VisualStyleElement.Window.CloseButton.Normal;
                }
            }

            // The left mouse button is not down.
            else
            {
                // Paint the close button hot if the cursor is on it.
                Rectangle closeRectangle =
                    elementRectangles["windowClose"];
                windowElements["windowClose"] =
                    closeRectangle.Contains(e.Location) ?
                    VisualStyleElement.Window.CloseButton.Hot :
                    VisualStyleElement.Window.CloseButton.Normal;

                // Use a resizing cursor if the cursor is on the 
                // status grip.
                Rectangle gripRectangle =
                    elementRectangles["statusGripper"];
                this.Cursor = gripRectangle.Contains(e.Location) ?
                    Cursors.SizeNWSE : Cursors.Default;
            }

            Invalidate();
        }

        // Calculate and set the clipping region for the control  
        // so that the corners of the title bar are rounded.
        private void SetClipRegion()
        {
            if (!Application.RenderWithVisualStyles)
            {
                return;
            }

            using (Graphics g = this.CreateGraphics())
            {
                // Get the current region for the window caption.
                if (SetRenderer(windowElements["windowCaption"]))
                {
                    Region clipRegion = renderer.GetBackgroundRegion(
                        g, elementRectangles["windowCaption"]);

                    // Get the client rectangle, but exclude the region 
                    // of the window caption.
                    int height = (int)clipRegion.GetBounds(g).Height;
                    Rectangle nonCaptionRect = new Rectangle(
                        ClientRectangle.X,
                        ClientRectangle.Y + height,
                        ClientRectangle.Width,
                        ClientRectangle.Height - height);

                    // Add the rectangle to the caption region, and  
                    // make this region the form's clipping region.
                    clipRegion.Union(nonCaptionRect);
                    this.Region = clipRegion;
                }
            }
        }

        // Set the VisualStyleRenderer to a new element.
        private bool SetRenderer(VisualStyleElement element)
        {
            if (!VisualStyleRenderer.IsElementDefined(element))
            {
                return false;
            }

            if (renderer == null)
            {
                renderer = new VisualStyleRenderer(element);
            }
            else
            {
                renderer.SetParameters(element);
            }

            return true;
        }
    }
}
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports System.Windows.Forms.VisualStyles

Namespace VisualStyleRendererSample

    Class Form1
        Inherits Form

        Public Sub New()
            With Me
                .Size = New Size(800, 600)
                .Location = New Point(20, 20)
                .BackColor = Color.DarkGray
            End With
            Dim Window1 As New ImitationWindow()
            Controls.Add(Window1)
        End Sub

        <STAThread()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    End Class

    Public Class ImitationWindow
        Inherits Control

        Private windowElements As _
            New Dictionary(Of String, VisualStyleElement)
        Private elementRectangles As _
            New Dictionary(Of String, Rectangle)
        Private renderer As VisualStyleRenderer = Nothing
        Private closeButtonOffset As Point
        Private gripperSize As Size
        Private closeButtonSize As Size
        Private isResizing As Boolean = False
        Private isMoving As Boolean = False
        Private isClosing As Boolean = False
        Private captionHeight As Integer
        Private frameThickness As Integer
        Private statusHeight As Integer = 22
        Private originalClick As New Point()
        Private resizeOffset As New Point()

        Public Sub New()
            With Me
                .Location = New Point(50, 50)
                .Size = New Size(350, 300)
                .BackColor = Color.Azure
                .DoubleBuffered = True
                .MinimumSize = New Size(300, 200)
                .Font = SystemFonts.CaptionFont
                .Text = "Imitation Window"
            End With

            ' Create a collection of VisualStyleElement objects.
            With windowElements
                .Add("windowCaption", _
                    VisualStyleElement.Window.Caption.Active)
                .Add("windowBottom", _
                    VisualStyleElement.Window.FrameBottom.Active)
                .Add("windowLeft", _
                    VisualStyleElement.Window.FrameLeft.Active)
                .Add("windowRight", _
                    VisualStyleElement.Window.FrameRight.Active)
                .Add("windowClose", _
                    VisualStyleElement.Window.CloseButton.Normal)
                .Add("statusBar", _
                    VisualStyleElement.Status.Bar.Normal)
                .Add("statusGripper", _
                    VisualStyleElement.Status.Gripper.Normal)
            End With

            ' Get the sizes and location offsets for the window parts  
            ' as specified by the visual style, and then use this   
            ' information to calcualate the rectangles for each part.
            GetPartDetails()
            CalculateRectangles()
        End Sub

        ' Get the sizes and offsets for the window parts as specified 
        ' by the visual style.
        Private Sub GetPartDetails()
            ' Do nothing further if visual styles are not enabled.
            If Not Application.RenderWithVisualStyles Then
                Return
            End If

            Using g As Graphics = Me.CreateGraphics()
                ' Get the size and offset of the close button.
                If SetRenderer(windowElements("windowClose")) Then
                    closeButtonSize = _
                        renderer.GetPartSize(g, ThemeSizeType.True)
                    closeButtonOffset = _
                        renderer.GetPoint(PointProperty.Offset)
                End If

                ' Get the height of the window caption.
                If SetRenderer(windowElements("windowCaption")) Then
                    captionHeight = renderer.GetPartSize(g, _
                        ThemeSizeType.True).Height
                End If

                ' Get the thickness of the left, bottom, and right 
                ' window frame.
                If SetRenderer(windowElements("windowLeft")) Then
                    frameThickness = renderer.GetPartSize(g, _
                        ThemeSizeType.True).Width
                End If

                ' Get the size of the resizing gripper.
                If SetRenderer(windowElements("statusGripper")) Then
                    gripperSize = renderer.GetPartSize(g, _
                        ThemeSizeType.True)
                End If
            End Using
        End Sub

        ' Use the part metrics to determine the current size of the 
        ' rectangles for all of the window parts.
        Private Sub CalculateRectangles()

            Dim heightMinusFrame As Integer = _
                ClientRectangle.Height - frameThickness

            ' Calculate the window frame rectangles and add them
            ' to the Dictionary of rectangles.
            elementRectangles("windowCaption") = _
                New Rectangle(0, 0, ClientRectangle.Width, _
                captionHeight)
            elementRectangles("windowBottom") = _
                New Rectangle(0, heightMinusFrame, _
                ClientRectangle.Width, frameThickness)
            elementRectangles("windowLeft") = _
                New Rectangle(0, captionHeight, frameThickness, _
                heightMinusFrame - captionHeight)
            elementRectangles("windowRight") = _
                New Rectangle(ClientRectangle.Width - frameThickness, _
                captionHeight, frameThickness, _
                heightMinusFrame - captionHeight)

            ' Calculate the window button rectangle and add it
            ' to the Dictionary of rectangles.
            elementRectangles("windowClose") = _
                New Rectangle(ClientRectangle.Right + _
                closeButtonOffset.X - closeButtonSize.Width - frameThickness, closeButtonOffset.Y, _
                closeButtonSize.Width, closeButtonSize.Height)

            ' Calculate the status bar rectangles and add them
            ' to the Dictionary of rectangles.
            elementRectangles("statusBar") = _
                New Rectangle(frameThickness, _
                heightMinusFrame - statusHeight, _
                ClientRectangle.Width - 2 * frameThickness, _
                statusHeight)
            elementRectangles("statusGripper") = _
                New Rectangle(ClientRectangle.Right - _
                gripperSize.Width - frameThickness, _
                heightMinusFrame - gripperSize.Height, _
                gripperSize.Width, gripperSize.Height)
        End Sub

        Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            MyBase.OnPaint(e)

            ' Ensure that visual styles are supported.
            If Not Application.RenderWithVisualStyles Then
                Me.Text = "Visual styles are not enabled."
                TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _
                    Me.Location, Me.ForeColor)
                Return
            End If

            ' Set the clip region to define the curved corners of 
            ' the caption.
            SetClipRegion()

            ' Draw each part of the window.
            Dim entry As KeyValuePair(Of String, VisualStyleElement)
            For Each entry In windowElements
                If SetRenderer(entry.Value) Then
                    renderer.DrawBackground(e.Graphics, _
                        elementRectangles(entry.Key))
                End If
            Next entry

            ' Draw the caption text.
            TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _
                elementRectangles("windowCaption"), Color.White, _
                TextFormatFlags.VerticalCenter Or _
                TextFormatFlags.HorizontalCenter)
        End Sub

        ' Initiate dragging, resizing, or closing the imitation window.
        Private Sub ImitationWindow_MouseDown(ByVal sender As Object, _
            ByVal e As MouseEventArgs) Handles Me.MouseDown

            ' The user clicked the close button.
            If elementRectangles("windowClose"). _
                Contains(e.Location) Then

                windowElements("windowClose") = _
                    VisualStyleElement.Window.CloseButton.Pressed
                isClosing = True

            ' The user clicked the status grip.
            ElseIf elementRectangles("statusGripper"). _
                Contains(e.Location) Then

                isResizing = True
                Me.Cursor = Cursors.SizeNWSE
                resizeOffset.X = Me.Right - Me.Left - e.X
                resizeOffset.Y = Me.Bottom - Me.Top - e.Y

            ' The user clicked the window caption.
            ElseIf elementRectangles("windowCaption"). _
                Contains(e.Location) Then

                isMoving = True
                originalClick.X = e.X
                originalClick.Y = e.Y
            End If
            Invalidate()
        End Sub

        ' Stop any current resizing or moving actions.
        Private Sub ImitationWindow_MouseUp(ByVal sender As Object, _
            ByVal e As MouseEventArgs) Handles Me.MouseUp

            ' Stop moving the location of the window rectangles.
            If isMoving Then
                isMoving = False

            ' Change the cursor back to the default if the 
            ' user stops resizing.
            ElseIf isResizing Then
                isResizing = False

            ' Close the application if the user clicks the 
            ' close button.
            ElseIf elementRectangles("windowClose"). _
                Contains(e.Location) And isClosing Then
                Application.Exit()
            End If
        End Sub

        ' Handle resizing or moving actions.
        Private Sub ImitationWindow_MouseMove(ByVal sender As Object, _
            ByVal e As MouseEventArgs) Handles Me.MouseMove

            ' The left mouse button is down.
            If (MouseButtons.Left And e.Button) = _
                MouseButtons.Left Then

                ' Calculate the new control size if the user is  
                ' dragging the resizing grip.
                If isResizing Then
                    Me.Width = e.X + resizeOffset.X
                    Me.Height = e.Y + resizeOffset.Y
                    CalculateRectangles()

                ' Calculate the new location of the control if   
                ' the user is dragging the window caption.
                ElseIf isMoving Then
                    Dim XChange As Integer = Me.Location.X + _
                        (e.X - originalClick.X)
                    Dim YChange As Integer = Me.Location.Y + _
                        (e.Y - originalClick.Y)
                    Me.Location = New Point(XChange, YChange)

                ' Cancel the closing action if the user clicked and  
                ' held down on the close button, and has dragged the   
                ' pointer outside the button.
                ElseIf Not elementRectangles("windowClose"). _
                    Contains(e.Location) And isClosing Then

                    isClosing = False
                    windowElements("windowClose") = _
                        VisualStyleElement.Window.CloseButton.Normal
                End If

            ' The left mouse button is not down.
            Else
                ' Paint the close button hot if the cursor is on it.
                If elementRectangles("windowClose"). _
                    Contains(e.Location) Then
                    windowElements("windowClose") = _
                        VisualStyleElement.Window.CloseButton.Hot
                Else
                    windowElements("windowClose") = _
                        VisualStyleElement.Window.CloseButton.Normal
                End If

                ' Use a resizing cursor if the cursor is on the 
                ' status grip.
                If elementRectangles("statusGripper"). _
                    Contains(e.Location) Then
                    Me.Cursor = Cursors.SizeNWSE
                Else
                    Me.Cursor = Cursors.Default
                End If
            End If
            Invalidate()
        End Sub

        ' Calculate and set the clipping region for the control  
        ' so that the corners of the title bar are rounded.
        Private Sub SetClipRegion()
            If Not Application.RenderWithVisualStyles Then
                Return
            End If

            Using g As Graphics = Me.CreateGraphics()
                ' Get the current region for the window caption.
                If SetRenderer(windowElements("windowCaption")) Then
                    Dim clipRegion As Region = _
                        renderer.GetBackgroundRegion(g, _
                        elementRectangles("windowCaption"))

                    ' Get the client rectangle, but exclude the   
                    ' region of the window caption.
                    Dim height As Integer = _
                        CInt(clipRegion.GetBounds(g).Height)
                    Dim nonCaptionRect As _
                        New Rectangle(ClientRectangle.X, _
                        ClientRectangle.Y + height, _
                        ClientRectangle.Width, _
                        ClientRectangle.Height - height)

                    ' Add the rectangle to the caption region, and  
                    ' make this region the form's clipping region.
                    clipRegion.Union(nonCaptionRect)
                    Me.Region = clipRegion
                End If
            End Using
        End Sub

        ' Set the VisualStyleRenderer to a new element.
        Private Function SetRenderer(ByVal element As _
            VisualStyleElement) As Boolean

            If Not VisualStyleRenderer.IsElementDefined(element) Then
                Return False
            End If

            If renderer Is Nothing Then
                renderer = New VisualStyleRenderer(element)
            Else
                renderer.SetParameters(element)
            End If

            Return True
        End Function

    End Class
End Namespace

備註

System.Windows.Forms.VisualStyles命名空間會 VisualStyleElement 公開 物件,這些物件代表視覺化樣式所支援的所有控制項和使用者介面 (UI) 元素。 若要繪製或取得特定專案的相關資訊,您必須將 設定 VisualStyleRenderer 為您感興趣的專案。 會自動 VisualStyleRenderer 設定為 VisualStyleElement 建構函式中指定的 VisualStyleRenderer ,但您也可以呼叫 SetParameters 方法,將現有的 VisualStyleRenderer 設定為不同的專案。

若要繪製專案,請使用 DrawBackground 方法。 類別 VisualStyleRenderer 也包含 和 等 GetColor GetEnumValue 方法,可提供目前視覺化樣式如何定義專案的相關資訊。

VisualStyleRenderer 構函式和許多 VisualStyleRenderer 方法都會擲回例外狀況,除非在作業系統中啟用視覺化樣式,而且視覺化樣式會套用至應用程式視窗的工作區。 若要檢查這些條件,請使用 static IsSupported 屬性。

類別 VisualStyleRenderer 會從Windows 平臺 SDK的 Windows Shell 部分包裝視覺化樣式 (UxTheme) API 的功能。

建構函式

VisualStyleRenderer(String, Int32, Int32)

使用指定的類別、組件和狀態值,初始化 VisualStyleRenderer 類別的新執行個體。

VisualStyleRenderer(VisualStyleElement)

使用指定的 VisualStyleRenderer,初始化 VisualStyleElement 類別的新執行個體。

屬性

Class

取得目前視覺化樣式項目的類別名稱。

Handle

取得視覺化樣式項目之目前類別的唯一識別項。

IsSupported

取得值,指定作業系統是否正使用視覺化樣式繪製控制項。

LastHResult

取得由 VisualStyleRenderer 類別封裝之原生視覺化樣式 (UxTheme) API 方法傳回的最後一個錯誤碼。

Part

取得目前視覺化樣式項目的組件。

State

取得目前視覺化樣式項目的狀態。

方法

DrawBackground(IDeviceContext, Rectangle)

在指定的週框內繪製目前視覺化樣式項目的背景影像。

DrawBackground(IDeviceContext, Rectangle, Rectangle)

在指定的週框內繪製目前視覺化樣式項目的背景影像並裁剪至指定的裁剪方框。

DrawEdge(IDeviceContext, Rectangle, Edges, EdgeStyle, EdgeEffects)

繪製指定之週框的一或多個邊緣。

DrawImage(Graphics, Rectangle, Image)

在指定的界限內繪製指定的影像。

DrawImage(Graphics, Rectangle, ImageList, Int32)

在指定的界限內,繪製指定之 ImageList 中的影像。

DrawParentBackground(IDeviceContext, Rectangle, Control)

在指定的區域中繪製控制項父代的背景。

DrawText(IDeviceContext, Rectangle, String)

使用預設格式在指定的界限內繪製文字。

DrawText(IDeviceContext, Rectangle, String, Boolean)

在指定的界限中繪製文字,並選擇顯示暫止作用的文字選項。

DrawText(IDeviceContext, Rectangle, String, Boolean, TextFormatFlags)

在指定的週框中繪製文字,並選擇顯示暫止作用的文字選項和套用其他文字格式的選項。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetBackgroundContentRectangle(IDeviceContext, Rectangle)

傳回目前視覺化樣式項目之背景的內容區域。

GetBackgroundExtent(IDeviceContext, Rectangle)

傳回目前視覺化樣式項目的整個背景區域。

GetBackgroundRegion(IDeviceContext, Rectangle)

傳回目前視覺化樣式項目的背景區域。

GetBoolean(BooleanProperty)

為目前所視覺化樣式項目傳回指定的布林值屬性值。

GetColor(ColorProperty)

為目前的視覺化樣式項目傳回指定的色彩屬性值。

GetEnumValue(EnumProperty)

為目前的視覺化樣式項目傳回指定的列舉型別屬性值。

GetFilename(FilenameProperty)

為目前的視覺化樣式項目傳回指定的檔名屬性值。

GetFont(IDeviceContext, FontProperty)

為目前的視覺化樣式項目傳回指定的字型屬性值。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetInteger(IntegerProperty)

為目前的視覺化樣式項目傳回指定的整數屬性值。

GetMargins(IDeviceContext, MarginProperty)

為目前的視覺化樣式項目傳回指定的邊界屬性值。

GetPartSize(IDeviceContext, Rectangle, ThemeSizeType)

使用指定所繪製界限,傳回目前視覺化樣式組件之指定的大小屬性值。

GetPartSize(IDeviceContext, ThemeSizeType)

為目前的視覺化樣式組件傳回指定的大小屬性值。

GetPoint(PointProperty)

為目前的視覺化樣式項目傳回指定的點屬性值。

GetString(StringProperty)

為目前的視覺化樣式項目傳回指定的字串屬性值。

GetTextExtent(IDeviceContext, Rectangle, String, TextFormatFlags)

當使用目前視覺化樣式項目的字型在指定的初始週框內繪製時,傳回指定的字串大小和位置。

GetTextExtent(IDeviceContext, String, TextFormatFlags)

當使用目前視覺化樣式項目的字型繪製時,傳回指定的字串大小和位置。

GetTextMetrics(IDeviceContext)

擷取目前視覺化樣式項目指定之字型的資訊。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
HitTestBackground(Graphics, Rectangle, Region, Point, HitTestOptions)

傳回點擊測試程式碼 (Hit-Test Code),指出點是否包含在目前視覺化樣式項目的背景和指定的界限中。

HitTestBackground(IDeviceContext, Rectangle, IntPtr, Point, HitTestOptions)

傳回點擊測試程式碼,指出點是否包含在目前視覺化樣式項目的背景和指定的區域中。

HitTestBackground(IDeviceContext, Rectangle, Point, HitTestOptions)

傳回點擊測試程式碼,指出目前視覺化樣式項目的背景中是否包含點。

IsBackgroundPartiallyTransparent()

指出目前視覺化樣式項目的背景是否有任何半透明或 Alpha 混合片段。

IsElementDefined(VisualStyleElement)

判斷指定的視覺化樣式項目是否由目前視覺化樣式定義。

MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
SetParameters(String, Int32, Int32)

將這個 VisualStyleRenderer 設為由指定之類別、組件和狀態值表示的視覺化樣式項目。

SetParameters(VisualStyleElement)

將這個 VisualStyleRenderer 設為由指定之 VisualStyleElement 表示的視覺化樣式項目。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

另請參閱