红联Linux门户
Linux帮助

Qt C++编程实现Windows和Ubuntu桌面背景/壁纸的设置

发布时间:2017-06-03 09:39:22来源:polarbear_TXMY作者:tfy.hi@163.com
本人对桌面背景的要求相对较高,而且希望能每天更换,但又觉得常规步骤太过麻烦(从网上找图片->下载至本地->打开本地路径->右键设为壁纸),所以想要写一个程序自动实现其全部过程。
为了能够通过程序实现后半部分功能,即设置本地目录下的图片为壁纸,特此查找到了windows系统下的相关API函数。另外由于本人还常使用Ubuntu系统,于是就将程序跨平台地扩展至了该系统,大体上的实现方法就是调用了一个SHELL文件。两系统的具体实现详见下文。
 
本人亲测平台: Win10,Ubuntu16.04LTS
运行环境:Qt5.7.0
 
Windows
调用API函数:SystemParametersInfo。该函数含有4个参数,只需更改第1项和第3项参数,分别为桌面壁纸标志SPI_SETDESKWALLPAPER和壁纸的本地存储路径filename。
#include <windows.h>
void WallPaper::setWallPaper(QString filePath)
{
const char *tmp = filePath.toStdString().c_str(); 
std::wstringstream wss;
wss << tmp;
const wchar_t *filename = wss.str().c_str();
if( !SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)filename, SPIF_UPDATEINIFILE) )//调用windows的API函数
qDebug("设置桌面背景失败!");
}
注:本人已测试 win10可调用此函数实现其功能。但win7会将桌面背景变成纯黑色。若读者发现有win7的解决方法,望指点。
 
Ubuntu
鉴于Ubuntu的相关API函数使用难度较大,需要安装一些库,过程太过繁琐。这里介绍一种比较简单的实现方法,即Qt的C++与SHELL结合使用来实现此功能:
1.在本project的目录下,单独存了一个SHELL文件。该SHELL中主要包含了一个图片路径变量和设置Ubuntu桌面背景的相关指令。
2.使用QFile设置更改SHELL文件中当前的图片路径。
3.使用QProcess执行此SHELL文件,更换壁纸。注:该SHELL文件的右键属性权限中应设置为“允许作为程序执行文件”。
Qt程序:
#include <QProcess>
void WallPaper::setWallPaper(QString filePath)
{
//更改SHELL文件“setwallpaperforUbuntu”中的图片路径信息
QFile file(qApp->applicationDirPath() + "/setwallpaperforUbuntu");
file.open(QIODevice::ReadWrite);
QTextStream textStream(&file);
QString text = textStream.readAll();
int start = text.indexOf("/home");
textStream.seek(start);
textStream << filePath << "'           ";//这么多空格是因为每次路径字符串长度不等,保证能够覆盖。SHELL文件相应位置也有空格(empty spaces)
file.close();
//调用执行该SHELL文件
QProcess *setWallPaperSHELL = new QProcess;
QString command = qApp->applicationDirPath() + "/setwallpaperforUbuntu";
setWallPaperSHELL->start(command);
}
SHELL文件“setwallpaperforUbuntu”:
#!/bin/bash
# Set picture options
# Valid options are: none,wallpaper,centered,scaled,stretched,zoom,span ned
picOpts="zoom"
# File Path, the location where the Bing pics are stored, NOTICE: there are many empty spaces after the ".jpg'", which is very necessary!
filePath='/home/yinhe/Pictures/WaldkauzDE_ZH-CN10024135858_1920x1080.jpg' 
# Set the GNOME3 wallpaper
DISPLAY=:0 GSETTINGS_BACKEND=dconf gsettings set org.gnome.desktop.background picture-uri '"file://'$filePath'"'
# Set the GNOME 3 wallpaper picture options
DISPLAY=:0 GSETTINGS_BACKEND=dconf gsettings set org.gnome.desktop.background picture-options $picOpts
# Exit the script
exit
 
Github代码:
一款简约的壁纸设置程序:https://github.com/polarbear0330/DeskWallPaper
Qt C++编程实现Windows和Ubuntu桌面背景/壁纸的设置
 
本文永久更新地址:http://www.linuxdiyf.com/linux/31229.html