WPF 製作 Windows 屏保

来源:https://www.cnblogs.com/yanjinhua/archive/2022/07/26/16519908.html
-Advertisement-
Play Games

分享如何使用WPF 製作 Windows 屏保 WPF 製作 Windows 屏保 作者:驚鏵 原文鏈接:https://github.com/yanjinhuagood/ScreenSaver 框架使用.NET452; Visual Studio 2019; 項目使用 MIT 開源許可協議; 更多 ...


分享如何使用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/


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.認識REST 1.1什麼是REST REST是軟體架構的規範體繫結構,它將資源的狀態以適合客戶端的形式從伺服器端發送到客戶端(或相反方向)。在REST中,通過URL進行資源定位,用HTTP動作GET、POST、DELETE、PUSH等)描述操作,完成功能。 道循RESTful風格,可以使開發的接 ...
  • 1. ElasticSearch快速入門 1.1. 基本介紹 ElasticSearch特色 Elasticsearch是實時的分散式搜索分析引擎,內部使用Lucene做索引與搜索 實時性:新增到 ES 中的數據在1秒後就可以被檢索到,這種新增數據對搜索的可見性稱為“準實時搜索” 分散式:意味著可以 ...
  • 選擇結構 if 選擇結構 語法 if(布爾表達式) { //當布爾表達式為true將執行的語句 } if(布爾表達式) { //當布爾表達式為true將執行的語句 }else{ //當布爾表達式為false時執行的語句 } if(條件1) { //條件1為ture時執行的語句 }else if(條件 ...
  • 前言 當我們使用DI方式寫了很多的Service後, 可能會發現我們的有些做法並不是最優的. 獲取註入的對象, 大家經常在構造函數中獲取, 這樣也是官方推薦的方式, 但有時不是效率最高的方法. 如果在構造函數中獲取對象,那麼每次對象的初始化都會把構造函數中的對象初始化一遍, 如果某個方法只用到其中一 ...
  • Word中設置水印時,可使用預設的文字或自定義文字設置為水印效果,但通常添加水印效果時,會對所有頁面都設置成統一效果,如果需要對每一頁或者某個頁面設置不同的水印效果,則可以參考本文中的方法。下麵,將以C# 代碼為例,對Word每一頁設置不同的文字水印效果作詳細介紹。 方法思路 在給Word每一頁添加 ...
  • 在日常開發 webapi 時,我們往往會集成 swagger doc 進行 api 的文檔呈現,當api數量比較多的時候就會導致 swagger ui 上的 api 因為數量太多而顯得雜亂,今天教大家如何利用 GroupName 屬性來對 api 的 Controller 進行分組,然後利用 swa ...
  • 我們知道,如果要對一個網站進行自動化測試,可以使用Python的selenium對獲取網頁的元素進行一系列操作。同樣,對於Windows應用,可以使用C#或者AutoIt(也是一種腳本語言,相比較與C#,AutoIt更適合做Windows應用的自動化腳本)捕獲窗體句柄進行操作。 今天主要記錄一下使用 ...
  • 所在單位有消息推送的需求,整理了一下,具體要求如下: 伺服器(ASP.NET)往桌面客戶端(WPF)單向推送; 客戶端消費消息分為一次性消費(如:掃面支付結果推送)、多次消費(如:訂單推送) ClientId線上狀態其他客戶端不能再用相同的ClientId連接 一開始使用了SingalR,缺點如下: ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...