2013-08-31 37 views
3

我希望能夠在WPF窗口內顯示屏幕保護程序的預覽。 (使用容器或控件或...)我知道Windows本身傳遞「/ p」參數給屏幕保護程序以獲得預覽。但是如何在WPF應用程序中顯示該預覽?我應該得到一個處理它,並將其父母更改爲我的容器控制?怎麼樣?如何在WPF窗口內顯示屏幕保護程序預覽

回答

2

您需要使用Windows.Forms互操作,因爲屏幕保護程序需要Windows句柄(HWND),並且在WPF中只有頂級窗口具有它們。

MainWindow.xaml

<Window x:Class="So18547663WpfScreenSaverPreview.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
     Title="Screen Saver Preview" Height="350" Width="525" 
     Loaded="MainWindow_OnLoaded" Closed="MainWindow_OnClosed" 
     SizeToContent="WidthAndHeight"> 
    <StackPanel Orientation="Vertical" Margin="8"> 
     <TextBlock Text="Preview"/> 
     <WindowsFormsHost x:Name="host" Width="320" Height="240"> 
      <forms:Control Width="320" Height="240"/> 
     </WindowsFormsHost> 
    </StackPanel> 
</Window> 

MainWindow.xaml.cs

using System; 
using System.Diagnostics; 
using System.Windows; 

namespace So18547663WpfScreenSaverPreview 
{ 
    public partial class MainWindow 
    { 
     private Process saver; 

     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void MainWindow_OnLoaded (object sender, RoutedEventArgs e) 
     { 
      saver = Process.Start(new ProcessStartInfo { 
       FileName = "Bubbles.scr", 
       Arguments = "/p " + host.Child.Handle, 
       UseShellExecute = false, 
      }); 
     } 

     private void MainWindow_OnClosed (object sender, EventArgs e) 
     { 
      // Optional. Screen savers should close themselves 
      // when the parent window is destroyed. 
      saver.Kill(); 
     } 
    } 
} 

集的引用

  • WindowsFormsIntegration
  • System.Windows.Forms

相關鏈接

+0

非常感謝。完美的作品。 – SepehrM

+0

更新的代碼,現在更少的代碼隱藏。 'Windows.Forms.Control'在XAML中創建。這是我第一次使用Windows Forms互操作;看起來像MSDN上的指令使事情變得複雜一點。 – Athari

+0

saver.Kill();是必要的!在我的測試中,它並沒有關閉。 – SepehrM

相關問題