WPF 製作 Windows 屏保

分享如何使用WPF 製作 Windows 屏保

WPF 製作 Windows 屏保

作者:驚鏵

原文鏈接:https://github.com/yanjinhuagood/ScreenSaver

  • 框架使用.NET452

  • Visual Studio 2019;

  • 項目使用 MIT 開源許可協議;

  • 更多效果可以通過GitHub[1]|碼雲[2]下載代碼;

  • 也可以自行添加天氣信息等。

正文

  • 屏保程序的本質上就是一個 Win32 窗口應用程序;

    • 把編譯好一個窗口應用程序之後,把擴展名更改爲 scr,於是你的屏幕保護程序就做好了;
    • 選中修改好的 scr 程序上點擊右鍵,可以看到一個 安裝 選項,點擊之後就安裝了;
    • 安裝之後會立即看到我們的屏幕保護程序已經運行起來了;
  • 處理屏幕保護程序參數如下

    • /s 屏幕保護程序開始,或者用戶點擊了 預覽 按鈕;
    • /c 用戶點擊了 設置按鈕;
    • /p 用戶選中屏保程序之後,在預覽窗格中顯示;

1)MainWindow.xaml 代碼如下;

<Window x:Class="ScreenSaver.MainWindow"
        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:system="clr-namespace:System;assembly=mscorlib"
        xmlns:drawing="http://www.microsoft.net/drawing"
        xmlns:local="clr-namespace:ScreenSaver"
        mc:Ignorable="d" WindowStyle="None"
        Title="MainWindow" Height="450" Width="800">

    <Grid x:Name="MainGrid">
        <drawing:PanningItems ItemsSource="{Binding stringCollection,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
                              x:Name="MyPanningItems">

            <drawing:PanningItems.ItemTemplate>
                <DataTemplate>
                    <Rectangle>
                        <Rectangle.Fill>
                            <ImageBrush ImageSource="{Binding .}"/>
                        </Rectangle.Fill>
                    </Rectangle>
                </DataTemplate>
            </drawing:PanningItems.ItemTemplate>
        </drawing:PanningItems>
        <Grid  HorizontalAlignment="Center" 
               VerticalAlignment="Top"
                Margin="0,50,0,0">

            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="FontSize" Value="90"/>
                    <Setter Property="FontWeight" Value="Black"/>
                    <Setter Property="Foreground" Value="White"/>
                
</Style>
            </Grid.Resources>
            <WrapPanel>
                <TextBlock Text="{Binding Hour,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"/>
                <TextBlock Text=":" x:Name="PART_TextBlock">
                    <TextBlock.Triggers>
                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="00:00:01"
                                                 From="1"
                                                 To="0"
                                                 Storyboard.TargetName="PART_TextBlock"
                                                 Storyboard.TargetProperty="Opacity"
                                                 RepeatBehavior="Forever"
                                                 FillBehavior="Stop"/>

                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </TextBlock.Triggers>
                </TextBlock>
                <TextBlock Text="{Binding Minute,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"/>
            </WrapPanel>
            <TextBlock Grid.Row="1" FontSize="45" HorizontalAlignment="Center" Text="{Binding Date,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"/>
        </Grid>
    </Grid>
</Window>

2) MainWindow.xaml.cs 代碼如下;

  • 當屏保啓動後需要注意如下
    • 將鼠標設置爲不可見Cursors.None;
    • 將窗體設置爲最大化WindowState.Maximized;
    • WindowStyle設置爲"None";
    • 注意監聽鼠標按下鍵盤按鍵則退出屏保;
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace ScreenSaver
{
    /// <summary>
    ///     MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty stringCollectionProperty =
            DependencyProperty.Register("stringCollection"typeof(ObservableCollection<string>), typeof(MainWindow),
                new PropertyMetadata(null));

        public static readonly DependencyProperty HourProperty =
            DependencyProperty.Register("Hour"typeof(string), typeof(MainWindow), new PropertyMetadata(null));

        public static readonly DependencyProperty MinuteProperty =
            DependencyProperty.Register("Minute"typeof(string), typeof(MainWindow), new PropertyMetadata(null));

        public static readonly DependencyProperty SecondProperty =
            DependencyProperty.Register("Second"typeof(string), typeof(MainWindow), new PropertyMetadata(null));

        public static readonly DependencyProperty DateProperty =
            DependencyProperty.Register("Date"typeof(string), typeof(MainWindow), new PropertyMetadata());

        private readonly DispatcherTimer timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();
            Loaded += delegate
            {
                WindowState = WindowState.Maximized;
                Mouse.OverrideCursor = Cursors.None;
                var date = DateTime.Now;
                Hour = date.ToString("HH");
                Minute = date.ToString("mm");
                Date =
                    $"{date.Month} / {date.Day}   {CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(date.DayOfWeek)}";
                stringCollection = new ObservableCollection<string>();
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
                var directoryInfo = new DirectoryInfo(path);
                foreach (var item in directoryInfo.GetFiles())
                {
                    if (Path.GetExtension(item.Name) != ".jpg"continue;
                    stringCollection.Add(item.FullName);
                }

                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += delegate
                {
                    date = DateTime.Now;
                    Hour = date.ToString("HH");
                    Minute = date.ToString("mm");
                    Date =
                        $"{date.Month} / {date.Day}   {CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(date.DayOfWeek)}";
                };
                timer.Start();
            };
            MouseDown += delegate { Application.Current.Shutdown(); };
            KeyDown += delegate { Application.Current.Shutdown(); };
        }

        public ObservableCollection<string> stringCollection
        {
            get => (ObservableCollection<string>)GetValue(stringCollectionProperty);
            set => SetValue(stringCollectionProperty, value);
        }


        public string Hour
        {
            get => (string)GetValue(HourProperty);
            set => SetValue(HourProperty, value);
        }

        public string Minute
        {
            get => (string)GetValue(MinuteProperty);
            set => SetValue(MinuteProperty, value);
        }

        public string Second
        {
            get => (string)GetValue(SecondProperty);
            set => SetValue(SecondProperty, value);
        }


        public string Date
        {
            get => (string)GetValue(DateProperty);
            set => SetValue(DateProperty, value);
        }
    }
}

參考①[3] 參考②[4]

參考資料

[1]

GitHub: https://github.com/yanjinhuagood/ScreenSaver

[2]

碼雲: https://gitee.com/yanjinhua/ScreenSaver

[3]

參考①: https://blog.walterlv.com/post/write-a-windows-screen-saver-using-wpf.html

[4]

參考②: https://wbsimms.com/create-screensaver-net-wpf/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章