c# - 定期更换桌面墙纸

标签 c# winforms

我在使用以下代码设置桌面墙纸时遇到问题。 SystemParametersInfo 返回 true 但它不会更改墙纸。它和以前一样,没有任何变化。但我希望代码从 *.bmp 文件目录中定期更改墙纸。请让我知道我在哪里犯了错误。

class Program
{
    [DllImport("user32.dll")]
    public static extern bool SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, string pvParam, UInt32 fWinIni);
    static FileInfo[] images;
    static int currentImage;

    static void Main(string[] args)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(@"C:/users/Smart-PC/Desktop");
        images = dirInfo.GetFiles("*.bmp", SearchOption.TopDirectoryOnly);

        currentImage = 0;

        System.Timers.Timer imageChangeTimer = new Timer(5000);
        imageChangeTimer.Elapsed += new ElapsedEventHandler(imageChangeTimer_Elapsed);
        imageChangeTimer.Start();

        Console.ReadLine();
    }

    static void imageChangeTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        const uint SPI_SETDESKWALLPAPER = 30;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;
        bool gk;
        gk = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, images[currentImage++].FullName, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
        Console.Write(gk);
        Console.WriteLine(images[currentImage].FullName);
        currentImage = (currentImage >= images.Length) ? 0 : currentImage;
    }
}

最佳答案

我刚刚测试了这个,它对我有用。顺便说一句,根据操作系统的不同,它仅适用于位图,如果您要尝试任何其他格式,则需要转换为位图。

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String         pvParam, UInt32 fWinIni);
        private static UInt32 SPI_SETDESKWALLPAPER = 20;
        private static UInt32 SPIF_UPDATEINIFILE = 0x1;
        private static String imageFileName = "c:\\test\\test.bmp";

        static void Main(string[] args)
        {
            SetImage(imageFileName);
            Console.ReadKey();
        }

        private static void SetImage(string filename)
        {
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, filename, SPIF_UPDATEINIFILE);
        }
    }
}

关于c# - 定期更换桌面墙纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15051245/

相关文章:

c# - 如何修复用户控件中的闪烁

c# - Linq OrderBy 不对原始集合进行排序吗?

c# - 如何将 QueueUserWorkItem 与 ref/out 状态一起使用?

c# - DataProtectionProvider构造函数保护说明

c# - 为什么 C# 的 String.Join 不在某一时刻使用 StringBuilder?

c# - 如何在 Windows 窗体应用程序中实现键盘按键

c# - 如何克隆一个 treeview c# 并保存它以便以后恢复

c# - 调用 Dispose 后释放对该组件的所有引用

c# - 带有EF Core Linq2Sql的聚合的聚合

c# - 为什么 bool 在使用传统绑定(bind)时无需转换器就可以实现可见性