將Flash 嵌入WPF 程序
由于WPF 本身中不支持COM 組件同時也無法加載ActiveX 控件,所以需要借助WinForm 引用ActiveX 控件將Flash 加入其中。首先創建一個WPF 項目(WpfFlash),將Flash 文件(.swf)加入到項目中,并將Copy to Output Directory 設置為"Copy always"。
在工程中新增一個Windows Forms Control Library 項目(FlashControlLibrary),利用該控件庫加載Flash ActiveX。
在FlashControlLibrary 項目工具欄(Toolbox)中點擊鼠標右鍵,選擇"Choose Items..."。在COM Components 標簽中選擇"Shockwave Flash Object",點擊確定。
此時在工具欄中已經可以看到剛添加的Shockwave Flash Object 控件了。將控件拖入設計窗口,調整好控件尺寸使其滿足Flash 的尺寸大小,對FlashControlLibrary 項目進行編譯,并生成DLL 文件。
返回WpfFlash 項目將上面編譯的AxInterop.ShockwaveFlashObjects.dll 加入References,并添加System.Windows.Forms 和WindowsFormsIntegration,便于WinForm 程序在WPF 中交互使用。
接下來將通過兩種方式將Flash 文件加入到WPF,一種側重于使用XAML 代碼實現,另一種則使用C#。可按各自需要選擇其一。
XAML 方法
打開MainWindow.xaml,加入命名空間xmlns:f="clr-namespace:AxShockwaveFlashObjects;assembly=AxInterop.ShockwaveFlashObjects"。在<Grid>中加入WindowsFormsHost 用于調用WinForm 程序,并在其中添加AxShockwaveFlash 控件加載Flash 文件。
<Window x:Class="WpfFlash.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:f="clr-namespace:AxShockwaveFlashObjects;assembly= AxInterop.ShockwaveFlashObjects" Title="Crab Shooter" Height="540" Width="655"> <Grid> <WindowsFormsHost> <f:AxShockwaveFlash x:Name="flashShow"/> </WindowsFormsHost> </Grid> </Window>
打開MainWindow.xaml.cs 將Flash 文件加載到flashShow 控件。
using System; using System.Windows; namespace WpfFlash { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); string flashPath = Environment.CurrentDirectory; flashPath += @"\game.swf"; flashShow.Movie = flashPath; } } }
C# 方法
使用C# 實現相同的效果,首先將XAML 代碼按如下方式修改,在Window 中加入Loaded 事件。
<Window x:Class="WpfFlash.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Crab Shooter" Loaded="FlashLoaded" Height="540" Width="655"> <Grid x:Name="mainGrid"/> </Window>
定義FlashLoaded 方法,主要通過WindowsFormsHost和 AxShockwaveFlash 完成Flash 加載操作。
using System; using System.Windows; using System.Windows.Forms.Integration; using AxShockwaveFlashObjects; namespace WpfFlash { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void FlashLoaded(object sender, RoutedEventArgs e) { WindowsFormsHost formHost = new WindowsFormsHost(); AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash(); formHost.Child = axShockwaveFlash; mainGrid.Children.Add(formHost); string flashPath = Environment.CurrentDirectory; flashPath += @"\game.swf"; axShockwaveFlash.Movie = flashPath; } } }