Export (0) Print
Expand All

VisualStyleRenderer Class

Provides methods for drawing and getting information about a VisualStyleElement. This class cannot be inherited.

System::Object
  System.Windows.Forms.VisualStyles::VisualStyleRenderer

Namespace:  System.Windows.Forms.VisualStyles
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public ref class VisualStyleRenderer sealed

The VisualStyleRenderer type exposes the following members.

  NameDescription
Public methodVisualStyleRenderer(VisualStyleElement)Initializes a new instance of the VisualStyleRenderer class using the given VisualStyleElement.
Public methodVisualStyleRenderer(String, Int32, Int32)Initializes a new instance of the VisualStyleRenderer class using the given class, part, and state values.
Top

  NameDescription
Public propertyClassGets the class name of the current visual style element.
Public propertyHandleGets a unique identifier for the current class of visual style elements.
Public propertyStatic memberIsSupportedGets a value specifying whether the operating system is using visual styles to draw controls.
Public propertyLastHResultGets the last error code returned by the native visual styles (UxTheme) API methods encapsulated by the VisualStyleRenderer class.
Public propertyPartGets the part of the current visual style element.
Public propertyStateGets the state of the current visual style element.
Top

  NameDescription
Public methodDrawBackground(IDeviceContext, Rectangle)Draws the background image of the current visual style element within the specified bounding rectangle.
Public methodDrawBackground(IDeviceContext, Rectangle, Rectangle)Draws the background image of the current visual style element within the specified bounding rectangle and clipped to the specified clipping rectangle.
Public methodDrawEdgeDraws one or more edges of the specified bounding rectangle.
Public methodDrawImage(Graphics, Rectangle, Image)Draws the specified image within the specified bounds.
Public methodDrawImage(Graphics, Rectangle, ImageList, Int32)Draws the image from the specified ImageList within the specified bounds.
Public methodDrawParentBackgroundDraws the background of a control's parent in the specified area.
Public methodDrawText(IDeviceContext, Rectangle, String)Draws text in the specified bounds using default formatting.
Public methodDrawText(IDeviceContext, Rectangle, String, Boolean)Draws text in the specified bounds with the option of displaying disabled text.
Public methodDrawText(IDeviceContext, Rectangle, String, Boolean, TextFormatFlags)Draws text in the specified bounding rectangle with the option of displaying disabled text and applying other text formatting.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetBackgroundContentRectangleReturns the content area for the background of the current visual style element.
Public methodGetBackgroundExtentReturns the entire background area for the current visual style element.
Public methodGetBackgroundRegionReturns the region for the background of the current visual style element.
Public methodGetBooleanReturns the value of the specified Boolean property for the current visual style element.
Public methodGetColorReturns the value of the specified color property for the current visual style element.
Public methodGetEnumValueReturns the value of the specified enumerated type property for the current visual style element.
Public methodGetFilenameReturns the value of the specified file name property for the current visual style element.
Public methodGetFontReturns the value of the specified font property for the current visual style element.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetIntegerReturns the value of the specified integer property for the current visual style element.
Public methodGetMarginsReturns the value of the specified margins property for the current visual style element.
Public methodGetPartSize(IDeviceContext, ThemeSizeType)Returns the value of the specified size property of the current visual style part.
Public methodGetPartSize(IDeviceContext, Rectangle, ThemeSizeType)Returns the value of the specified size property of the current visual style part using the specified drawing bounds.
Public methodGetPointReturns the value of the specified point property for the current visual style element.
Public methodGetStringReturns the value of the specified string property for the current visual style element.
Public methodGetTextExtent(IDeviceContext, String, TextFormatFlags)Returns the size and location of the specified string when drawn with the font of the current visual style element.
Public methodGetTextExtent(IDeviceContext, Rectangle, String, TextFormatFlags)Returns the size and location of the specified string when drawn with the font of the current visual style element within the specified initial bounding rectangle.
Public methodGetTextMetricsRetrieves information about the font specified by the current visual style element.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodHitTestBackground(IDeviceContext, Rectangle, Point, HitTestOptions)Returns a hit test code indicating whether a point is contained in the background of the current visual style element.
Public methodHitTestBackground(Graphics, Rectangle, Region, Point, HitTestOptions)Returns a hit test code indicating whether the point is contained in the background of the current visual style element and within the specified bounds.
Public methodHitTestBackground(IDeviceContext, Rectangle, IntPtr, Point, HitTestOptions)Returns a hit test code indicating whether the point is contained in the background of the current visual style element and within the specified region.
Public methodIsBackgroundPartiallyTransparentIndicates whether the background of the current visual style element has any semitransparent or alpha-blended pieces.
Public methodStatic memberIsElementDefinedDetermines whether the specified visual style element is defined by the current visual style.
Public methodSetParameters(VisualStyleElement)Sets this VisualStyleRenderer to the visual style element represented by the specified VisualStyleElement.
Public methodSetParameters(String, Int32, Int32)Sets this VisualStyleRenderer to the visual style element represented by the specified class, part, and state values.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

The System.Windows.Forms.VisualStyles namespace exposes VisualStyleElement objects that represent all of the controls and user interface (UI) elements that are supported by visual styles. To draw or get information about a particular element, you must set a VisualStyleRenderer to the element you are interested in. A VisualStyleRenderer is automatically set to a specified VisualStyleElement in the VisualStyleRenderer constructor, but you can also set an existing VisualStyleRenderer to a different element by calling the SetParameters method.

To draw an element, use the DrawBackground method. The VisualStyleRenderer class also includes methods, such as GetColor and GetEnumValue, that provide information about how an element is defined by the current visual style.

The VisualStyleRenderer constructor and many of the VisualStyleRenderer methods throw exceptions unless visual styles are enabled in the operating system and visual styles are applied to the client area of application windows. To check for these conditions, use the static IsSupported property.

The VisualStyleRenderer class wraps the functionality of the visual styles (UxTheme) API from the Windows Shell portion of the Windows Platform SDK. For more information about visual styles, see "Using Windows XP Visual Styles" in the Platform SDK portion of the MSDN Library at http://msdn.microsoft.com/library.

Windows XP Home Edition, Windows XP Professional x64 Edition, Windows Server 2003 Platform Note: Visual styles are supported only on these platforms.

The following code example uses the VisualStyleRenderer class to implement a custom control that simulates some of the basic UI of a window, including dragging with the title bar, resizing with the sizing handle, and closing. This example uses several VisualStyleElement objects that represent standard parts of a window, including the elements exposed by the VisualStyleElement::Window::Caption, VisualStyleElement::Window::CloseButton, and VisualStyleElement::Status::Gripper classes.

#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, 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());
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft