Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » WPF » Shaped Windows in WPF

Shaped Windows in WPF

Every user interface in WPF is represented by a Window. In this article, you will learn how to create non-rectangular shaped Windows in WPF using C#.

Author Rank :
Page Views : 8284
Downloads : 185
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
NonRectWindowSample.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


If you come from Windows Forms background, you must have heard of shaped Windows Forms or non-rectangular Windows Forms. A non-rectangular Windows Forms has a user interface that is not a typical rectangular Window you see in Windows user interfaces. The window can be of any shape such as a drawing, a fruit, a stereo player and so on.

In WPF, there is no concept of Windows Forms. Every user interface in WPF is represented by a Window. In this article, you will learn how to create non-rectangular shaped Windows in WPF.

In Windows Forms, to create non-rectangular shaped Forms, we used to create a Path and used to set Path property of a Path.

Creating non-rectangular interfaces in WPF is actually simpler than Windows Forms. We just have to set AllowsTransparency property of a Window to True and Background to Transparent. After that whatever you place on that Window does not have a background typical Window in the background.

<Window x:Class="NonRectWindowSample.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1"

AllowsTransparency="True"

      Background="Transparent">

 

        

</Window>

 

So let's say we need to create a user interface that looks like Figure 1. We simply have to create a Path with the similar UI and place on a transparent Window. That will do the trick.

 ShapedWindowImg1.gif

Figure 1

The complete code of the Window in XAML looks like Listing 1.

<Window x:Class="NonRectWindowSample.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" SizeToContent="WidthAndHeight"

    MouseLeftButtonDown="Window_MouseLeftButtonDown"

      WindowStyle="None"

      AllowsTransparency="True"

      Background="Transparent">

 

    <Canvas Width="400" Height="400" Name="RootLayout" >

 

        <Path Stroke="Gray" StrokeThickness="2" Name="UIPath" >

            <Path.Fill>

                <LinearGradientBrush StartPoint="0.2,0" EndPoint="0.8,1" >

                    <GradientStop Color="Green" Offset="0" />

                    <GradientStop Color="Yellow"  Offset="0.35" />

                    <GradientStop Color="Orange" Offset="0.65" />

                    <GradientStop Color="Red" Offset="0.85" />

                </LinearGradientBrush>

            </Path.Fill>

 

            <Path.Data>

                <PathGeometry >

                    <PathFigure StartPoint="50,100">

                        <ArcSegment Size="150,150" RotationAngle="45" IsLargeArc="True"

                                    SweepDirection="CounterClockwise" Point="100,50" />

                        <LineSegment Point="20,20"/>

                    </PathFigure>

                </PathGeometry>

            </Path.Data>

        </Path>

 

        <Label Width="226" Height="68" FontSize="20" FontFamily="Georgia" FontWeight="Bold"

           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"

           Canvas.Left="60" Canvas.Top="127"

           Foreground="Blue" >

            Drag Me and Watch!

        </Label>

 

        <Button Canvas.Left="206" Canvas.Top="42" Height="0" Width="0"

            ToolTip="Click me to close the form." Name="CloseButton" Click="CloseButton_Click">

            <Button.Template>

                <ControlTemplate>

                    <Canvas>

                        <Rectangle Width="20" Height="20" Stroke="DarkBlue" RadiusX="2" RadiusY="2">

                            <Rectangle.Fill>

                                <SolidColorBrush x:Name="myAnimatedBrush" Color="Blue" />

                            </Rectangle.Fill>

                        </Rectangle>

                        <Line X1="3" Y1="3" X2="17" Y2="17" Stroke="White" StrokeThickness="2"></Line>

                        <Line X1="17" Y1="3" X2="3" Y2="17" Stroke="White" StrokeThickness="2"></Line>

                    </Canvas>

                </ControlTemplate>

            </Button.Template>

        </Button>

        <Button Canvas.Left="131" Canvas.Top="272" Height="30" Name="BlackNWhiteButton" Width="112"

               Foreground="White" Background="Crimson" Click="BlackNWhiteButton_Click" FontWeight="Bold">

            Black and White

        </Button>

    </Canvas>

   

</Window>

Listing 1

We also write code listed in Listing 2 for the left mouse button click event handler and call DragMove method of the Window that is responsible for moving a Window position when a Window is dragged. The Close button click event handler simply closes the Window.

On Black and White button click event handler, we change background of the Window to black and white color gradient.

private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

    this.DragMove();

}

 

private void CloseButton_Click(object sender, RoutedEventArgs e)

{

    this.Close();

}

 

private void BlackNWhiteButton_Click(object sender, RoutedEventArgs e)

{

        // Create a linear gradient brush with five stops 

    LinearGradientBrush blacknwhiteBrush = new LinearGradientBrush();

    blacknwhiteBrush.StartPoint = new Point(0, 0);

    blacknwhiteBrush.EndPoint = new Point(1, 1);

 

    // Create and add Gradient stops

    GradientStop blackGS = new GradientStop();

    blackGS.Color = Colors.Black;

    blackGS.Offset = 0.0;

    blacknwhiteBrush.GradientStops.Add(blackGS);

 

    GradientStop whiteGS = new GradientStop();

    whiteGS.Color = Colors.White;

    whiteGS.Offset = 1.0;

    blacknwhiteBrush.GradientStops.Add(whiteGS);

 

    UIPath.Fill = blacknwhiteBrush;

}

Listing 2

Clicking Black and White button changes the Window that looks like Figure 2.

ShapedWindowImg2.gif

Figure 2


Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Thanks! by danny On November 3, 2009
wow thanks man, I've been looking for something like this for a while now, I always wondered how they do these kinds of windows...

------------------------------------------
Danny, San Francisco Locksmith
Reply | Email | Modify 
Re: Thanks! by Mahesh On November 4, 2009
Now you know :).
Reply | Email | Modify 
Thanks!!! by Harold On November 5, 2009
Nice article. Thanks dude.
Reply | Email | Modify 
Window Shape by Chris On March 22, 2010
Can I refer to an image such as  BMP, JPEG or otherwsie for window geometry and/or  background?

Thank you!
Chris
Reply | Email | Modify 
Re: Window Shape by Mahesh On September 8, 2011
Yes you can set any image as background.
Reply | Email | Modify 
Thanks by zhang On July 31, 2011
very appreciated! cool article
Reply | Email | Modify 
Re: Thanks by Mahesh On September 8, 2011
Thanks guys!
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.