如何在WPF窗口中显示屏幕保护程序的预览

本文关键字:程序 屏幕保护 显示 WPF 窗口 | 更新日期: 2023-09-27 18:29:41

我希望能够在WPF窗口中显示屏幕保护程序的预览。(使用容器或控件或…)我知道Windows本身会将"/p"参数传递给屏幕保护程序以获得预览。但是如何在WPF应用程序中显示预览呢?我应该获得它的句柄并将它的父对象更改为我的容器o控件吗?怎样

如何在WPF窗口中显示屏幕保护程序的预览

您需要使用Windows.Forms互操作,因为屏幕保护程序需要窗口句柄(HWND),而在WPF中,只有顶级窗口才有它们。

主窗口.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>

主窗口.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

相关链接

  • 演练:在WPF中托管Windows窗体控件
  • 使用C#创建屏幕保护程序(描述命令行参数)