【问题标题】:How to show a preview of screen saver inside WPF window如何在 WPF 窗口中显示屏幕保护程序的预览
【发布时间】:2013-09-04 01:18:09
【问题描述】:

我希望能够在 WPF 窗口中显示屏幕保护程序的预览。 (使用容器或控件或...)我知道 Windows 本身将“/p”参数传递给屏幕保护程序以获取预览。但是如何在我的 WPF 应用程序中显示该预览?我应该处理它并将其父级更改为我的容器或控件吗?怎么样?

【问题讨论】:

    标签: c# wpf screensaver


    【解决方案1】:

    您需要使用 Windows.Forms 互操作,因为屏幕保护程序需要窗口句柄 (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

    相关链接

    【讨论】:

    • 非常感谢。完美运行。
    • 更新了代码,现在减少了代码隐藏。 Windows.Forms.Control 在 XAML 中创建。这是我第一次使用 Windows 窗体互操作;看起来 MSDN 上的说明有点复杂。
    • saver.Kill();有必要的!在我的测试中,它并没有自行关闭。
    • 如何在主机中加载另一个屏幕保护程序?我试过了:if(saver != null &amp;&amp; saver.HasExited == false) saver.Kill(); saver = new Process(); saver = Process.Start(new ProcessStartInfo { FileName = (comboScreenSavers.SelectedItem as ComboBoxItem).Tag.ToString(), Arguments = "/p " + hostScreenSaver.Child.Handle, UseShellExecute = false, }); 但是一团糟……
    • 如果我理解正确,你想避免杀死进程吗?屏幕保护程序在您的控件内创建一个子窗口。您可以尝试向其发送 WM_CLOSE 消息。不确定屏幕保护程序会响应它,但值得一试。
    猜你喜欢
    • 2015-08-29
    • 1970-01-01
    • 2012-04-08
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多