换桌面背景

前言

看到Demo中,在内存中做了一个位图文件, 按照参数写上文字内容,保存成bmp, 设置该bmp为桌面背景. 设置桌面背景只用一个API : SystemParametersInfo.
如果是一个后台程序,要显示一些提示性的信息,用墙纸和用户交互也是一个有趣的选择.

试验

// hw.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[])
{
    char szBuf[MAXBYTE] = {'\0'};

    for (int i = 0; i < 5; i++) {
        // 换桌面背景, 只支持bmp格式
        SystemParametersInfoA(
            SPI_SETDESKWALLPAPER, 
            0, 
            "D:\\pic\\1.bmp", 
            SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

        Sleep(3000); // 3秒换一张背景图片

        // 取消墙纸
        SystemParametersInfoA(
            SPI_SETDESKWALLPAPER, 
            0, 
            szBuf, 
            SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

        Sleep(3000); // 3秒换一张背景图片
    }

    return 0;
}
可以使用C#中的SystemParametersInfo函数来获取和更Windows桌面背景。具体步骤如下: 1. 获取当前桌面背景路径: ```csharp StringBuilder sb = new StringBuilder(256); bool result = SystemParametersInfo(SPI_GETDESKWALLPAPER, 256, sb, 0); if (result) { string path = sb.ToString(); } ``` 2. 更桌面背景: ```csharp bool result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, "newImagePath", SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); if (!result) { // 更桌面背景失败 } ``` 其中,`SPI_SETDESKWALLPAPER`表示设置桌面背景,`SPI_GETDESKWALLPAPER`表示获取当前桌面背景。 `SPIF_UPDATEINIFILE`和`SPIF_SENDWININICHANGE`是一些标志位,用于更新系统设置并立即生效。 需要引入以下命名空间: ```csharp using System.Runtime.InteropServices; using System.Text; ``` 完整代码示例: ```csharp using System.Runtime.InteropServices; using System.Text; public class DesktopBackground { [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SystemParametersInfo(int uAction, int uParam, StringBuilder lpvParam, int fuWinIni); private const int SPI_GETDESKWALLPAPER = 0x0073; private const int SPI_SETDESKWALLPAPER = 0x0014; private const int SPIF_UPDATEINIFILE = 0x01; private const int SPIF_SENDWININICHANGE = 0x02; public static string GetDesktopBackground() { StringBuilder sb = new StringBuilder(256); bool result = SystemParametersInfo(SPI_GETDESKWALLPAPER, 256, sb, 0); if (result) { return sb.ToString(); } else { return null; } } public static bool SetDesktopBackground(string imagePath) { bool result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imagePath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); return result; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值