原文 http://www.cnblogs.com/ListenFly/archive/2013/02/19/2917744.html
<Window x:Class="mumu_nonRectangularwindow.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" SizeToContent="WidthAndHeight" MouseLeftButtonDown="Window_MouseLeftButtonDown"> <!--視窗的形狀都繪製在Canvas面板裡面--> <Canvas Width="200" Height="200" > <!--視窗的輪廓--> <Path Stroke="DarkGray" StrokeThickness="2"> <Path.Fill> <LinearGradientBrush StartPoint="0.2,0" EndPoint="0.8,1" > <GradientStop Color="White" Offset="0"></GradientStop> <GradientStop Color="White" Offset="0.45"></GradientStop> <GradientStop Color="LightBlue" Offset="0.9"></GradientStop> <GradientStop Color="Gray" Offset="1"></GradientStop> </LinearGradientBrush> </Path.Fill> <Path.Data> <PathGeometry> <PathFigure StartPoint="40,20" IsClosed="True"> <LineSegment Point="160,20"></LineSegment> <ArcSegment Point="180,40" Size="20,20" SweepDirection="Clockwise"></ArcSegment> <LineSegment Point="180,80"></LineSegment> <ArcSegment Point="160,100" Size="20,20" SweepDirection="Clockwise"></ArcSegment> <LineSegment Point="90,100"></LineSegment> <LineSegment Point="90,150"></LineSegment> <LineSegment Point="60,100"></LineSegment> <LineSegment Point="40,100"></LineSegment> <ArcSegment Point="20,80" Size="20,20" SweepDirection="Clockwise"></ArcSegment> <LineSegment Point="20,40"></LineSegment> <ArcSegment Point="40,20" Size="20,20" SweepDirection="Clockwise"></ArcSegment> </PathFigure> </PathGeometry> </Path.Data> </Path> <!--“拖拽我!”的標籤--> <Label Width="200" Height="120" FontSize="15" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">Drag Me</Label> <!--關閉按鈕--> <Button Canvas.Left="155" Canvas.Top="30" Click="Button_Click"> <Button.Template> <ControlTemplate> <Canvas> <Rectangle Width="15" Height="15" Stroke="Black" RadiusX="3" RadiusY="3"> <Rectangle.Fill> <SolidColorBrush x:Name="myAnimatedBrush" Color="Red" /> </Rectangle.Fill> </Rectangle> <Line X1="3" Y1="3" X2="12" Y2="12" Stroke="White" StrokeThickness="2"></Line> <Line X1="12" Y1="3" X2="3" Y2="12" Stroke="White" StrokeThickness="2"></Line> </Canvas> </ControlTemplate> </Button.Template> </Button> </Canvas></Window>
介面代碼如上,後台代碼如下:
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { this.DragMove(); } private void Button_Click(object sender, RoutedEventArgs e) { this.Close(); }
後台代碼比較簡單,一個是自訂關閉按鈕的事件,一個為滑鼠左鍵按下事件(按下後可拖動表單)。
如下:
可是會發現,可預期的效果有點不一樣,因為預期的是自訂的表單,而不是依賴於表單的自訂圖形,所以還需要如下的設定
Background="Transparent" AllowsTransparency="True" WindowStyle="None"
設定表單背景色為透明;同時設定AllowsTransparency為true,表示視窗的客戶區支援透明色;同時刪除最小化最大化和關閉按鈕,所以設定WindowsStyle為None,最終的效果
如下:
可以拖動表單,同時也可以按下紅叉關閉表單,最重要是他的確是一個不規則的自訂表單.
其實自訂表單的實現原理很簡單,由一個Path和一個Button(通過模板繪製出紅叉),Path繪製出了訊息框的圖形,Button實現了關閉功能。