[源码下载]
作者: webabcd
介绍
Silverlight 4.0 OOB 之 被信任的应用程序:
在线DEMO
http://www.cnblogs.com/webabcd/archive/2010/08/09/1795417.html
示例
1、关于“被信任的应用程序”的简要概述
Demo.xaml
代码
2、访问本地文件系统的 Demo
AccessLocalFile.xaml
代码
AccessLocalFile.xaml.cs
代码
3、通过调用 Excel API(COM 接口)的方式,将数据导出为 Excel 格式
COMDemo.xaml
代码
COMDemo.xaml.cs
代码
4、自定义窗口样式和行为的 Demo(详见 CustomOOBWindow 项目)
generic.xaml
代码
MyWindow.cs
代码
MainPage.xaml
代码
OK
[源码下载] <script type="text/javascript"> if ($ != jQuery) { $ = jQuery.noConflict(); } </script>
稳扎稳打Silverlight(45) - 4.0浏览器外运行(Out Of Browser)之被信任的应用程序(Trusted Application)
作者: webabcd
介绍
Silverlight 4.0 OOB 之 被信任的应用程序:
- 概述
- 访问本地文件系统
- 调用 COM 接口
- 自定义窗口样式和行为
在线DEMO
http://www.cnblogs.com/webabcd/archive/2010/08/09/1795417.html
示例
1、关于“被信任的应用程序”的简要概述
Demo.xaml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<
navigation:Page
x:Class
="Silverlight40.TrustedApplication.Demo"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title ="Other Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< TextBlock Margin ="5" Text ="被信任的应用程序 - 对浏览器外应用程序提升信任级别。在 Silverlight 项目上单击右键 -> 属性 -> Silverlight -> Out-of-Browser Settings -> 选中 Require elevated trust when running outside the browser" />
< TextBlock Margin ="5" Text ="Application.Current.HasElevatedPermissions - 判断 OOB 模式中的应用程序是否为被信任的应用程序" />
< TextBlock Margin ="5" Text ="无需策略文件即可跨域通信,TCP通信端口不再限制为4502-4534" />
< TextBlock Margin ="5" Text ="全屏后,按 ESC 键应用程序将不会退出全屏模式" />
< TextBlock Margin ="5" Text ="应用程序签名:使用工具 SignTool.exe" />
< TextBlock Margin ="5" Text ="访问本地文件系统:详见本目录下的 AccessLocalFile.xaml" />
< TextBlock Margin ="5" Text ="调用 COM 接口:详见本目录下的 COMDemo..xaml" />
< TextBlock Margin ="5" Text ="自定义窗口:详见本解决方案的 CustomOOBWindow 项目" />
</ StackPanel >
</ Grid >
</ navigation:Page >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title ="Other Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< TextBlock Margin ="5" Text ="被信任的应用程序 - 对浏览器外应用程序提升信任级别。在 Silverlight 项目上单击右键 -> 属性 -> Silverlight -> Out-of-Browser Settings -> 选中 Require elevated trust when running outside the browser" />
< TextBlock Margin ="5" Text ="Application.Current.HasElevatedPermissions - 判断 OOB 模式中的应用程序是否为被信任的应用程序" />
< TextBlock Margin ="5" Text ="无需策略文件即可跨域通信,TCP通信端口不再限制为4502-4534" />
< TextBlock Margin ="5" Text ="全屏后,按 ESC 键应用程序将不会退出全屏模式" />
< TextBlock Margin ="5" Text ="应用程序签名:使用工具 SignTool.exe" />
< TextBlock Margin ="5" Text ="访问本地文件系统:详见本目录下的 AccessLocalFile.xaml" />
< TextBlock Margin ="5" Text ="调用 COM 接口:详见本目录下的 COMDemo..xaml" />
< TextBlock Margin ="5" Text ="自定义窗口:详见本解决方案的 CustomOOBWindow 项目" />
</ StackPanel >
</ Grid >
</ navigation:Page >
2、访问本地文件系统的 Demo
AccessLocalFile.xaml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<
navigation:Page
x:Class
="Silverlight40.TrustedApplication.AccessLocalFile"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title ="AccessLocalFile Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< TextBlock Text ="在不使用 OpenFileDialog 和 SaveFileDialog 的情况下,访问 MyDocuments, MyMusic, MyPictures, MyVideos 文件夹" />
<!-- 显示“我的文档”中的文件夹列表 -->
< ListBox Name ="listBoxDirectory" HorizontalAlignment ="Left" >
< ListBox.ItemTemplate >
< DataTemplate >
< StackPanel Orientation ="Horizontal" >
< TextBlock Text =" {Binding Name} " Margin ="1" />
</ StackPanel >
</ DataTemplate >
</ ListBox.ItemTemplate >
</ ListBox >
<!-- 显示“我的文档”中的文件列表 -->
< ListBox Name ="listBoxFile" HorizontalAlignment ="Left" >
< ListBox.ItemTemplate >
< DataTemplate >
< StackPanel Orientation ="Horizontal" >
< TextBlock Text =" {Binding Name} " Margin ="1" />
</ StackPanel >
</ DataTemplate >
</ ListBox.ItemTemplate >
</ ListBox >
</ StackPanel >
</ Grid >
</ navigation:Page >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title ="AccessLocalFile Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< TextBlock Text ="在不使用 OpenFileDialog 和 SaveFileDialog 的情况下,访问 MyDocuments, MyMusic, MyPictures, MyVideos 文件夹" />
<!-- 显示“我的文档”中的文件夹列表 -->
< ListBox Name ="listBoxDirectory" HorizontalAlignment ="Left" >
< ListBox.ItemTemplate >
< DataTemplate >
< StackPanel Orientation ="Horizontal" >
< TextBlock Text =" {Binding Name} " Margin ="1" />
</ StackPanel >
</ DataTemplate >
</ ListBox.ItemTemplate >
</ ListBox >
<!-- 显示“我的文档”中的文件列表 -->
< ListBox Name ="listBoxFile" HorizontalAlignment ="Left" >
< ListBox.ItemTemplate >
< DataTemplate >
< StackPanel Orientation ="Horizontal" >
< TextBlock Text =" {Binding Name} " Margin ="1" />
</ StackPanel >
</ DataTemplate >
</ ListBox.ItemTemplate >
</ ListBox >
</ StackPanel >
</ Grid >
</ navigation:Page >
AccessLocalFile.xaml.cs
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
/*
* 访问本地文件系统的 Demo,只能访问“我的文档”,“我的音乐”,“我的图片”,“我的视频” 文件夹
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
namespace Silverlight40.TrustedApplication
{
public partial class AccessLocalFile : Page
{
public AccessLocalFile()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if ( ! App.Current.IsRunningOutOfBrowser)
{
MessageBox.Show( " 请在OOB中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
// Application.Current.HasElevatedPermissions - 判断 OOB 模式中的应用程序是否为被信任的应用程序
if (Application.Current.HasElevatedPermissions)
{
/*
* GetFolderPath(Environment.SpecialFolder folder) - 获取指定的文件夹的路径
* Environment.SpecialFolder - Windows 操作系统中特殊文件夹的枚举(在被信任程序中使用)
* Environment.SpecialFolder.MyDocuments - 我的文档。可以在被信任程序中访问
* Environment.SpecialFolder.MyMusic - 我的音乐。可以在被信任程序中访问
* Environment.SpecialFolder.MyPictures - 我的图片。可以在被信任程序中访问
* Environment.SpecialFolder.MyVideos - 我的视频。可以在被信任程序中访问
* Environment.SpecialFolder 还有其他很多枚举值,详见文档
* 针对文件夹操作和文件操的类有:Directory, DirectoryInfo, File, FileInfo, FileStream, Path, StreamReader, StreamWriter
*/
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
DirectoryInfo root = new DirectoryInfo(path);
// 我的文档中的文件夹
listBoxDirectory.ItemsSource = root.EnumerateDirectories();
// 我的文档中的文件
listBoxFile.ItemsSource = root.EnumerateFiles();
}
}
}
}
* 访问本地文件系统的 Demo,只能访问“我的文档”,“我的音乐”,“我的图片”,“我的视频” 文件夹
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
namespace Silverlight40.TrustedApplication
{
public partial class AccessLocalFile : Page
{
public AccessLocalFile()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if ( ! App.Current.IsRunningOutOfBrowser)
{
MessageBox.Show( " 请在OOB中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
// Application.Current.HasElevatedPermissions - 判断 OOB 模式中的应用程序是否为被信任的应用程序
if (Application.Current.HasElevatedPermissions)
{
/*
* GetFolderPath(Environment.SpecialFolder folder) - 获取指定的文件夹的路径
* Environment.SpecialFolder - Windows 操作系统中特殊文件夹的枚举(在被信任程序中使用)
* Environment.SpecialFolder.MyDocuments - 我的文档。可以在被信任程序中访问
* Environment.SpecialFolder.MyMusic - 我的音乐。可以在被信任程序中访问
* Environment.SpecialFolder.MyPictures - 我的图片。可以在被信任程序中访问
* Environment.SpecialFolder.MyVideos - 我的视频。可以在被信任程序中访问
* Environment.SpecialFolder 还有其他很多枚举值,详见文档
* 针对文件夹操作和文件操的类有:Directory, DirectoryInfo, File, FileInfo, FileStream, Path, StreamReader, StreamWriter
*/
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
DirectoryInfo root = new DirectoryInfo(path);
// 我的文档中的文件夹
listBoxDirectory.ItemsSource = root.EnumerateDirectories();
// 我的文档中的文件
listBoxFile.ItemsSource = root.EnumerateFiles();
}
}
}
}
3、通过调用 Excel API(COM 接口)的方式,将数据导出为 Excel 格式
COMDemo.xaml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<
navigation:Page
x:Class
="Silverlight40.TrustedApplication.COMDemo"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:sdk ="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Title ="COMDemo Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< Button Name ="btnExport" Content ="导出到 Excel" Click ="btnExport_Click" />
< sdk:DataGrid Name ="dataGrid" HorizontalAlignment ="Left" VerticalAlignment ="Top" Width ="400" Height ="300" IsReadOnly ="True" AutoGenerateColumns ="True" />
</ StackPanel >
</ Grid >
</ navigation:Page >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:sdk ="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Title ="COMDemo Page" >
< Grid x:Name ="LayoutRoot" >
< StackPanel HorizontalAlignment ="Left" >
< Button Name ="btnExport" Content ="导出到 Excel" Click ="btnExport_Click" />
< sdk:DataGrid Name ="dataGrid" HorizontalAlignment ="Left" VerticalAlignment ="Top" Width ="400" Height ="300" IsReadOnly ="True" AutoGenerateColumns ="True" />
</ StackPanel >
</ Grid >
</ navigation:Page >
COMDemo.xaml.cs
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
/*
* 此例用于演示:通过调用 Excel API(COM 接口)的方式,将数据导出为 Excel 格式
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices.Automation;
namespace Silverlight40.TrustedApplication
{
public partial class COMDemo : Page
{
public COMDemo()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if ( ! App.Current.IsRunningOutOfBrowser)
{
MessageBox.Show( " 请在 OOB 中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
else if ( ! Application.Current.HasElevatedPermissions)
{
MessageBox.Show( " 请在 “被信任的应用程序” 中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
dataGrid.ItemsSource = GetProducts();
}
private void btnExport_Click( object sender, RoutedEventArgs e)
{
dynamic excelApp = typeof (Object);
try
{
/*
* AutomationFactory.IsAvailable - 获取一个值,该值表示 AutomationFactory 是否可用
* AutomationFactory.CreateObject() - 根据编程标识符(ProgID)激活指定的组件,并返回该引用
* AutomationFactory.GetObject() - 根据编程标识符(ProgID)获取已激活的并且当前正在运行的组件引用
*/
if ( ! AutomationFactory.IsAvailable)
{
MessageBox.Show( " 无法调用 COM 接口 " );
return ;
}
// 激活并获取 Excel.Application 引用
excelApp = AutomationFactory.CreateObject( " Excel.Application " );
}
catch (Exception ex)
{
MessageBox.Show( " 没有安装 Excel ? " + ex.Message);
}
excelApp.Visible = true ;
// 新开一个工作簿
dynamic workbook = excelApp.Workbooks;
workbook.Add();
// 当前工作表
dynamic sheet = excelApp.ActiveSheet;
dynamic cell = null ;
int index = 1 ;
foreach (Product p in dataGrid.ItemsSource)
{
cell = sheet.Cells[index, 1 ];
cell.Value = p.ProductId;
// 获取指定了行列的单元格
cell = sheet.Cells[index, 2 ];
// 单元格内要显示的内容
cell.Value = p.Name;
// 设置单元格背景颜色为红色。这里的 16 位颜色值为 BGR
cell.Interior.Color = 0x0000FF ;
cell = sheet.Cells[index, 3 ];
cell.Value = p.Price;
index ++ ;
}
}
// 数据源
private ObservableCollection < Product > GetProducts()
{
return new ObservableCollection < Product >
{
new Product{ ProductId = 1 , Name = " ProductName01 " , Price = 100.6m },
new Product{ ProductId = 2 , Name = " ProductName02 " , Price = 60.8m },
new Product{ ProductId = 3 , Name = " ProductName03 " , Price = 189.2m },
new Product{ ProductId = 4 , Name = " ProductName04 " , Price = 56m},
new Product{ ProductId = 5 , Name = " ProductName05 " , Price = 69m},
new Product{ ProductId = 6 , Name = " ProductName06 " , Price = 244m},
};
}
}
// 实体类
public class Product
{
public int ProductId { get ; set ; }
public string Name { get ; set ; }
public decimal Price { get ; set ; }
}
}
* 此例用于演示:通过调用 Excel API(COM 接口)的方式,将数据导出为 Excel 格式
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices.Automation;
namespace Silverlight40.TrustedApplication
{
public partial class COMDemo : Page
{
public COMDemo()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if ( ! App.Current.IsRunningOutOfBrowser)
{
MessageBox.Show( " 请在 OOB 中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
else if ( ! Application.Current.HasElevatedPermissions)
{
MessageBox.Show( " 请在 “被信任的应用程序” 中运行 " );
LayoutRoot.Visibility = Visibility.Collapsed;
}
dataGrid.ItemsSource = GetProducts();
}
private void btnExport_Click( object sender, RoutedEventArgs e)
{
dynamic excelApp = typeof (Object);
try
{
/*
* AutomationFactory.IsAvailable - 获取一个值,该值表示 AutomationFactory 是否可用
* AutomationFactory.CreateObject() - 根据编程标识符(ProgID)激活指定的组件,并返回该引用
* AutomationFactory.GetObject() - 根据编程标识符(ProgID)获取已激活的并且当前正在运行的组件引用
*/
if ( ! AutomationFactory.IsAvailable)
{
MessageBox.Show( " 无法调用 COM 接口 " );
return ;
}
// 激活并获取 Excel.Application 引用
excelApp = AutomationFactory.CreateObject( " Excel.Application " );
}
catch (Exception ex)
{
MessageBox.Show( " 没有安装 Excel ? " + ex.Message);
}
excelApp.Visible = true ;
// 新开一个工作簿
dynamic workbook = excelApp.Workbooks;
workbook.Add();
// 当前工作表
dynamic sheet = excelApp.ActiveSheet;
dynamic cell = null ;
int index = 1 ;
foreach (Product p in dataGrid.ItemsSource)
{
cell = sheet.Cells[index, 1 ];
cell.Value = p.ProductId;
// 获取指定了行列的单元格
cell = sheet.Cells[index, 2 ];
// 单元格内要显示的内容
cell.Value = p.Name;
// 设置单元格背景颜色为红色。这里的 16 位颜色值为 BGR
cell.Interior.Color = 0x0000FF ;
cell = sheet.Cells[index, 3 ];
cell.Value = p.Price;
index ++ ;
}
}
// 数据源
private ObservableCollection < Product > GetProducts()
{
return new ObservableCollection < Product >
{
new Product{ ProductId = 1 , Name = " ProductName01 " , Price = 100.6m },
new Product{ ProductId = 2 , Name = " ProductName02 " , Price = 60.8m },
new Product{ ProductId = 3 , Name = " ProductName03 " , Price = 189.2m },
new Product{ ProductId = 4 , Name = " ProductName04 " , Price = 56m},
new Product{ ProductId = 5 , Name = " ProductName05 " , Price = 69m},
new Product{ ProductId = 6 , Name = " ProductName06 " , Price = 244m},
};
}
}
// 实体类
public class Product
{
public int ProductId { get ; set ; }
public string Name { get ; set ; }
public decimal Price { get ; set ; }
}
}
4、自定义窗口样式和行为的 Demo(详见 CustomOOBWindow 项目)
generic.xaml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<
ResourceDictionary
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:CustomOOBWindow" >
< Style TargetType ="local:MyWindow" >
< Setter Property ="Template" >
< Setter.Value >
< ControlTemplate TargetType ="local:MyWindow" >
< Border x:Name ="windowBorder" BorderBrush ="Green" Background ="Red" BorderThickness ="2" CornerRadius ="5" >
< Grid x:Name ="layoutRoot" >
<!-- 窗口的上下左右都留出 5 个像素的边框 -->
< Grid.ColumnDefinitions >
< ColumnDefinition Width ="5" />
< ColumnDefinition Width ="*" />
< ColumnDefinition Width ="5" />
</ Grid.ColumnDefinitions >
< Grid.RowDefinitions >
< RowDefinition Height ="5" />
< RowDefinition Height ="*" />
< RowDefinition Height ="5" />
</ Grid.RowDefinitions >
<!-- 在窗口的 4 个边和 4 个角上放置透明的矩形,用于当通过鼠标改变窗口大小时,鼠标移动到边或角上时改变鼠标的样式 -->
< Grid.Resources >
< Style TargetType ="Rectangle" >
< Setter Property ="Fill" Value ="Transparent" />
</ Style >
</ Grid.Resources >
< Rectangle x:Name ="topLeftCorner" Grid.Row ="0" Grid.Column ="0" Cursor ="SizeNWSE" />
< Rectangle x:Name ="topEdge" Grid.Row ="0" Grid.Column ="1" Cursor ="SizeNS" />
< Rectangle x:Name ="topRightCorner" Grid.Row ="0" Grid.Column ="2" Cursor ="SizeNESW" />
< Rectangle x:Name ="leftEdge" Grid.Row ="1" Grid.Column ="0" Cursor ="SizeWE" />
< Rectangle x:Name ="rightEdge" Grid.Row ="1" Grid.Column ="2" Cursor ="SizeWE" />
< Rectangle x:Name ="bottomLeftCorner" Grid.Row ="2" Grid.Column ="0" Cursor ="SizeNESW" />
< Rectangle x:Name ="bottomEdge" Grid.Row ="2" Grid.Column ="1" Cursor ="SizeNS" />
< Rectangle x:Name ="bottomRightCorner" Grid.Row ="2" Grid.Column ="2" Cursor ="SizeNWSE" />
< Grid Grid.Row ="1" Grid.Column ="1" >
< Grid.RowDefinitions >
< RowDefinition Height ="Auto" />
< RowDefinition Height ="*" />
</ Grid.RowDefinitions >
< Grid x:Name ="titleBar" Margin ="0,0,0,3" >
< Grid.Resources >
< Style TargetType ="Button" >
< Setter Property ="Width" Value ="20" />
< Setter Property ="Height" Value ="20" />
< Setter Property ="Padding" Value ="0" />
</ Style >
</ Grid.Resources >
< Grid.ColumnDefinitions >
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="*" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
</ Grid.ColumnDefinitions >
<!-- 窗口的图标和标题 -->
< Image x:Name ="windowIcon" Grid.Column ="0" Width ="16" Height ="16" />
< TextBlock x:Name ="title" Grid.Column ="1" FontSize ="12" Padding ="5,0,0,0" />
<!-- 总在最前按钮,最小化按钮,最大化按钮,关闭按钮 -->
< ToggleButton x:Name ="pinButton" Grid.Column ="2" Width ="80" Content ="总在最前" />
< Button x:Name ="minButton" Grid.Column ="3" Width ="80" Content ="最小化" />
< ToggleButton x:Name ="maxButton" Grid.Column ="4" Width ="80" Content ="最大化" />
< Button x:Name ="closeButton" Grid.Column ="5" Width ="80" Content ="关闭" />
</ Grid >
<!--
ContentPresenter - 窗口内的内容
-->
< Border Background ="White" Grid.Row ="1" BorderBrush ="Blue" BorderThickness ="2" >
< ContentPresenter />
</ Border >
</ Grid >
</ Grid >
</ Border >
</ ControlTemplate >
</ Setter.Value >
</ Setter >
</ Style >
</ ResourceDictionary >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:CustomOOBWindow" >
< Style TargetType ="local:MyWindow" >
< Setter Property ="Template" >
< Setter.Value >
< ControlTemplate TargetType ="local:MyWindow" >
< Border x:Name ="windowBorder" BorderBrush ="Green" Background ="Red" BorderThickness ="2" CornerRadius ="5" >
< Grid x:Name ="layoutRoot" >
<!-- 窗口的上下左右都留出 5 个像素的边框 -->
< Grid.ColumnDefinitions >
< ColumnDefinition Width ="5" />
< ColumnDefinition Width ="*" />
< ColumnDefinition Width ="5" />
</ Grid.ColumnDefinitions >
< Grid.RowDefinitions >
< RowDefinition Height ="5" />
< RowDefinition Height ="*" />
< RowDefinition Height ="5" />
</ Grid.RowDefinitions >
<!-- 在窗口的 4 个边和 4 个角上放置透明的矩形,用于当通过鼠标改变窗口大小时,鼠标移动到边或角上时改变鼠标的样式 -->
< Grid.Resources >
< Style TargetType ="Rectangle" >
< Setter Property ="Fill" Value ="Transparent" />
</ Style >
</ Grid.Resources >
< Rectangle x:Name ="topLeftCorner" Grid.Row ="0" Grid.Column ="0" Cursor ="SizeNWSE" />
< Rectangle x:Name ="topEdge" Grid.Row ="0" Grid.Column ="1" Cursor ="SizeNS" />
< Rectangle x:Name ="topRightCorner" Grid.Row ="0" Grid.Column ="2" Cursor ="SizeNESW" />
< Rectangle x:Name ="leftEdge" Grid.Row ="1" Grid.Column ="0" Cursor ="SizeWE" />
< Rectangle x:Name ="rightEdge" Grid.Row ="1" Grid.Column ="2" Cursor ="SizeWE" />
< Rectangle x:Name ="bottomLeftCorner" Grid.Row ="2" Grid.Column ="0" Cursor ="SizeNESW" />
< Rectangle x:Name ="bottomEdge" Grid.Row ="2" Grid.Column ="1" Cursor ="SizeNS" />
< Rectangle x:Name ="bottomRightCorner" Grid.Row ="2" Grid.Column ="2" Cursor ="SizeNWSE" />
< Grid Grid.Row ="1" Grid.Column ="1" >
< Grid.RowDefinitions >
< RowDefinition Height ="Auto" />
< RowDefinition Height ="*" />
</ Grid.RowDefinitions >
< Grid x:Name ="titleBar" Margin ="0,0,0,3" >
< Grid.Resources >
< Style TargetType ="Button" >
< Setter Property ="Width" Value ="20" />
< Setter Property ="Height" Value ="20" />
< Setter Property ="Padding" Value ="0" />
</ Style >
</ Grid.Resources >
< Grid.ColumnDefinitions >
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="*" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
< ColumnDefinition Width ="Auto" />
</ Grid.ColumnDefinitions >
<!-- 窗口的图标和标题 -->
< Image x:Name ="windowIcon" Grid.Column ="0" Width ="16" Height ="16" />
< TextBlock x:Name ="title" Grid.Column ="1" FontSize ="12" Padding ="5,0,0,0" />
<!-- 总在最前按钮,最小化按钮,最大化按钮,关闭按钮 -->
< ToggleButton x:Name ="pinButton" Grid.Column ="2" Width ="80" Content ="总在最前" />
< Button x:Name ="minButton" Grid.Column ="3" Width ="80" Content ="最小化" />
< ToggleButton x:Name ="maxButton" Grid.Column ="4" Width ="80" Content ="最大化" />
< Button x:Name ="closeButton" Grid.Column ="5" Width ="80" Content ="关闭" />
</ Grid >
<!--
ContentPresenter - 窗口内的内容
-->
< Border Background ="White" Grid.Row ="1" BorderBrush ="Blue" BorderThickness ="2" >
< ContentPresenter />
</ Border >
</ Grid >
</ Grid >
</ Border >
</ ControlTemplate >
</ Setter.Value >
</ Setter >
</ Style >
</ ResourceDictionary >
MyWindow.cs
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
/*
* 自定义 OOB 模式下的窗口样式和行为(需要配置为被信任的应用程序)
*/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
namespace CustomOOBWindow
{
public class MyWindow : ContentControl
{
/*
* 在 Out-of-Browser Settings 可以设置 Window Style。背景不可透明,所以不能创建不规则形状的应用程序
* Default - 默认样式
* No Border - 无边框
* Borderless Round Corners - 无边框,带圆角,圆角的角半径为 9 个像素
*/
private Grid layoutRoot;
private Border windowBorder;
private FrameworkElement titleBar;
public MyWindow()
{
if (Application.Current.IsRunningOutOfBrowser && ! DesignerProperties.IsInDesignTool)
{
/*
* Application.Current.MainWindow - OOB 模式下的应用程序窗口。属性值为 System.Windows.Window 类型
* Window.Width - 窗口的宽
* Window.Height - 窗口的高
* Window.Top - 窗口距离屏幕顶部的距离
* Window.Left - 窗口距离屏幕左侧的距离
* Window.WindowState - 窗口状态 [System.Windows.WindowState 枚举]
* WindowState.Normal - 正常大小
* WindowState.Minimized - 最小化到任务栏
* WindowState.Maximized - 最大化,全屏
* Window.TopMost - 窗口是否总在最前面
* Window.Activate() - 激活窗口,使之具有焦点,并置于最前面
* Window.IsActive - 是否为激活窗口(仅 get)
* Window.DragMove() - 实现用鼠标拖动窗口的功能
* Window.DragResize(WindowResizeEdge resizeEdge) - 根据指定的 WindowResizeEdge 改变窗口的边或角的位置,也就是调整窗口大小
* Left, Right, Top, TopLeft, TopRight, Bottom, BottomLeft, BottomRight
*/
Window mainWindow = Application.Current.MainWindow;
mainWindow.Width = 640 ;
mainWindow.Height = 480 ;
// 在 Out-of-Browser Settings 选中“Set window location manually”时,这里的设置才会生效
mainWindow.Top = 100 ;
mainWindow.Left = 100 ;
mainWindow.WindowState = WindowState.Normal;
mainWindow.TopMost = false ;
}
// 设置控件的默认样式
this .DefaultStyleKey = typeof (MyWindow);
}
// UI 元素在应用程序中显示之前所调用的方法
public override void OnApplyTemplate()
{
base .OnApplyTemplate();
// Control.GetTemplateChild() - 在实例化的 ControlTemplate 可视化树中检索已命名的元素
layoutRoot = GetTemplateChild( " layoutRoot " ) as Grid;
windowBorder = GetTemplateChild( " windowBorder " ) as Border;
titleBar = GetTemplateChild( " titleBar " ) as FrameworkElement;
InitializeTitleBar();
InitializeButton();
InitializeWindowBorder();
}
private void InitializeTitleBar()
{
TextBlock title = GetTemplateChild( " title " ) as TextBlock;
title.Text = Deployment.Current.OutOfBrowserSettings.WindowSettings.Title;
Image windowIcon = GetTemplateChild( " windowIcon " ) as Image;
// 设置窗口左上角的图标
// Deployment.Current.OutOfBrowserSettings - 获取 OOB 的相关配置信息
if (Deployment.Current.OutOfBrowserSettings.Icons.Count > 0 )
windowIcon.Source = new System.Windows.Media.Imaging.BitmapImage( new Uri( " / " + Deployment.Current.OutOfBrowserSettings.Icons[ 0 ].Source.ToString(), UriKind.Relative));
else
windowIcon.Visibility = Visibility.Collapsed;
titleBar.MouseLeftButtonDown += delegate { Application.Current.MainWindow.DragMove(); };
}
private void InitializeButton()
{
Window mainWindow = Application.Current.MainWindow;
var pinButton = GetTemplateChild( " pinButton " ) as ToggleButton;
var minButton = GetTemplateChild( " minButton " ) as Button;
var maxButton = GetTemplateChild( " maxButton " ) as ToggleButton;
var closeButton = GetTemplateChild( " closeButton " ) as Button;
pinButton.Checked += delegate { mainWindow.TopMost = true ; pinButton.Content = " 常规窗口 " ; };
pinButton.Unchecked += delegate { mainWindow.TopMost = false ; pinButton.Content = " 总在最前 " ; };
minButton.Click += delegate { mainWindow.WindowState = WindowState.Minimized; };
maxButton.Checked += delegate { mainWindow.WindowState = WindowState.Maximized; maxButton.Content = " 正常化 " ; };
maxButton.Unchecked += delegate { mainWindow.WindowState = WindowState.Normal; maxButton.Content = " 最大化 " ; };
closeButton.Click += delegate { mainWindow.Close(); };
}
private void InitializeWindowBorder()
{
Window mainWindow = Application.Current.MainWindow;
UIElement topLeftCorner = GetTemplateChild( " topLeftCorner " ) as UIElement;
UIElement topEdge = GetTemplateChild( " topEdge " ) as UIElement;
UIElement topRightCorner = GetTemplateChild( " topRightCorner " ) as UIElement;
UIElement leftEdge = GetTemplateChild( " leftEdge " ) as UIElement;
UIElement rightEdge = GetTemplateChild( " rightEdge " ) as UIElement;
UIElement bottomLeftCorner = GetTemplateChild( " bottomLeftCorner " ) as UIElement;
UIElement bottomEdge = GetTemplateChild( " bottomEdge " ) as UIElement;
UIElement bottomRightCorner = GetTemplateChild( " bottomRightCorner " ) as UIElement;
topLeftCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.TopLeft); };
topEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Top); };
topRightCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.TopRight); };
leftEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Left); };
rightEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Right); };
bottomLeftCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.BottomLeft); };
bottomEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Bottom); };
bottomRightCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.BottomRight); };
}
}
}
* 自定义 OOB 模式下的窗口样式和行为(需要配置为被信任的应用程序)
*/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
namespace CustomOOBWindow
{
public class MyWindow : ContentControl
{
/*
* 在 Out-of-Browser Settings 可以设置 Window Style。背景不可透明,所以不能创建不规则形状的应用程序
* Default - 默认样式
* No Border - 无边框
* Borderless Round Corners - 无边框,带圆角,圆角的角半径为 9 个像素
*/
private Grid layoutRoot;
private Border windowBorder;
private FrameworkElement titleBar;
public MyWindow()
{
if (Application.Current.IsRunningOutOfBrowser && ! DesignerProperties.IsInDesignTool)
{
/*
* Application.Current.MainWindow - OOB 模式下的应用程序窗口。属性值为 System.Windows.Window 类型
* Window.Width - 窗口的宽
* Window.Height - 窗口的高
* Window.Top - 窗口距离屏幕顶部的距离
* Window.Left - 窗口距离屏幕左侧的距离
* Window.WindowState - 窗口状态 [System.Windows.WindowState 枚举]
* WindowState.Normal - 正常大小
* WindowState.Minimized - 最小化到任务栏
* WindowState.Maximized - 最大化,全屏
* Window.TopMost - 窗口是否总在最前面
* Window.Activate() - 激活窗口,使之具有焦点,并置于最前面
* Window.IsActive - 是否为激活窗口(仅 get)
* Window.DragMove() - 实现用鼠标拖动窗口的功能
* Window.DragResize(WindowResizeEdge resizeEdge) - 根据指定的 WindowResizeEdge 改变窗口的边或角的位置,也就是调整窗口大小
* Left, Right, Top, TopLeft, TopRight, Bottom, BottomLeft, BottomRight
*/
Window mainWindow = Application.Current.MainWindow;
mainWindow.Width = 640 ;
mainWindow.Height = 480 ;
// 在 Out-of-Browser Settings 选中“Set window location manually”时,这里的设置才会生效
mainWindow.Top = 100 ;
mainWindow.Left = 100 ;
mainWindow.WindowState = WindowState.Normal;
mainWindow.TopMost = false ;
}
// 设置控件的默认样式
this .DefaultStyleKey = typeof (MyWindow);
}
// UI 元素在应用程序中显示之前所调用的方法
public override void OnApplyTemplate()
{
base .OnApplyTemplate();
// Control.GetTemplateChild() - 在实例化的 ControlTemplate 可视化树中检索已命名的元素
layoutRoot = GetTemplateChild( " layoutRoot " ) as Grid;
windowBorder = GetTemplateChild( " windowBorder " ) as Border;
titleBar = GetTemplateChild( " titleBar " ) as FrameworkElement;
InitializeTitleBar();
InitializeButton();
InitializeWindowBorder();
}
private void InitializeTitleBar()
{
TextBlock title = GetTemplateChild( " title " ) as TextBlock;
title.Text = Deployment.Current.OutOfBrowserSettings.WindowSettings.Title;
Image windowIcon = GetTemplateChild( " windowIcon " ) as Image;
// 设置窗口左上角的图标
// Deployment.Current.OutOfBrowserSettings - 获取 OOB 的相关配置信息
if (Deployment.Current.OutOfBrowserSettings.Icons.Count > 0 )
windowIcon.Source = new System.Windows.Media.Imaging.BitmapImage( new Uri( " / " + Deployment.Current.OutOfBrowserSettings.Icons[ 0 ].Source.ToString(), UriKind.Relative));
else
windowIcon.Visibility = Visibility.Collapsed;
titleBar.MouseLeftButtonDown += delegate { Application.Current.MainWindow.DragMove(); };
}
private void InitializeButton()
{
Window mainWindow = Application.Current.MainWindow;
var pinButton = GetTemplateChild( " pinButton " ) as ToggleButton;
var minButton = GetTemplateChild( " minButton " ) as Button;
var maxButton = GetTemplateChild( " maxButton " ) as ToggleButton;
var closeButton = GetTemplateChild( " closeButton " ) as Button;
pinButton.Checked += delegate { mainWindow.TopMost = true ; pinButton.Content = " 常规窗口 " ; };
pinButton.Unchecked += delegate { mainWindow.TopMost = false ; pinButton.Content = " 总在最前 " ; };
minButton.Click += delegate { mainWindow.WindowState = WindowState.Minimized; };
maxButton.Checked += delegate { mainWindow.WindowState = WindowState.Maximized; maxButton.Content = " 正常化 " ; };
maxButton.Unchecked += delegate { mainWindow.WindowState = WindowState.Normal; maxButton.Content = " 最大化 " ; };
closeButton.Click += delegate { mainWindow.Close(); };
}
private void InitializeWindowBorder()
{
Window mainWindow = Application.Current.MainWindow;
UIElement topLeftCorner = GetTemplateChild( " topLeftCorner " ) as UIElement;
UIElement topEdge = GetTemplateChild( " topEdge " ) as UIElement;
UIElement topRightCorner = GetTemplateChild( " topRightCorner " ) as UIElement;
UIElement leftEdge = GetTemplateChild( " leftEdge " ) as UIElement;
UIElement rightEdge = GetTemplateChild( " rightEdge " ) as UIElement;
UIElement bottomLeftCorner = GetTemplateChild( " bottomLeftCorner " ) as UIElement;
UIElement bottomEdge = GetTemplateChild( " bottomEdge " ) as UIElement;
UIElement bottomRightCorner = GetTemplateChild( " bottomRightCorner " ) as UIElement;
topLeftCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.TopLeft); };
topEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Top); };
topRightCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.TopRight); };
leftEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Left); };
rightEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Right); };
bottomLeftCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.BottomLeft); };
bottomEdge.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.Bottom); };
bottomRightCorner.MouseLeftButtonDown += delegate { mainWindow.DragResize(WindowResizeEdge.BottomRight); };
}
}
}
MainPage.xaml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<
window:MyWindow
x:Class
="CustomOOBWindow.MainPage"
xmlns:window ="clr-namespace:CustomOOBWindow;assembly=CustomOOBWindow"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable ="d"
d:DesignHeight ="300" d:DesignWidth ="400" >
< Grid x:Name ="LayoutRoot" Background ="White" >
< TextBlock Text ="自定义 OOB 窗口的 Demo,需要设置为被信任的应用程序" />
</ Grid >
</ window:MyWindow >
xmlns:window ="clr-namespace:CustomOOBWindow;assembly=CustomOOBWindow"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable ="d"
d:DesignHeight ="300" d:DesignWidth ="400" >
< Grid x:Name ="LayoutRoot" Background ="White" >
< TextBlock Text ="自定义 OOB 窗口的 Demo,需要设置为被信任的应用程序" />
</ Grid >
</ window:MyWindow >
OK
[源码下载] <script type="text/javascript"> if ($ != jQuery) { $ = jQuery.noConflict(); } </script>