摘要:本人對(duì)桌面背景的要求相對(duì)較高,而且希望能每天更換,但又覺(jué)得常規(guī)步驟太過(guò)麻煩(從網(wǎng)上找圖片->下載至本地->打開(kāi)本地路徑->右鍵設(shè)為壁紙),所以想要寫(xiě)一個(gè)程序自動(dòng)實(shí)現(xiàn)其全部過(guò)程。(從網(wǎng)上爬取圖片的實(shí)現(xiàn)在其他文章另有介紹)(文末附完整源代碼的鏈接)
為了能夠通過(guò)程序?qū)崿F(xiàn)后半部分功能,即設(shè)置本地目錄下的圖片為壁紙,特此查找到了windows系統(tǒng)下的相關(guān)API函數(shù)。另外由于本人還常使用Ubuntu系統(tǒng),于是就將程序跨平臺(tái)地?cái)U(kuò)展至了該系統(tǒng),大體上的實(shí)現(xiàn)方法就是調(diào)用了一個(gè)SHELL文件。兩系統(tǒng)的具體實(shí)現(xiàn)詳見(jiàn)下文。
本人親測(cè)平臺(tái): Win10,Ubuntu16.04LTS
運(yùn)行環(huán)境:Qt5.7.0
Windows
調(diào)用API函數(shù):SystemParametersInfo。該函數(shù)含有4個(gè)參數(shù),只需更改第1項(xiàng)和第3項(xiàng)參數(shù),分別為桌面壁紙標(biāo)志SPI_SETDESKWALLPAPER和壁紙的本地存儲(chǔ)路徑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) )//調(diào)用windows的API函數(shù)
qDebug("設(shè)置桌面背景失敗!");
}
注:本人測(cè)試win10可調(diào)用此函數(shù)實(shí)現(xiàn)其功能。但win7會(huì)將桌面背景變成純黑色。若讀者發(fā)現(xiàn)有win7的解決方法,望指點(diǎn)。
Ubuntu
鑒于Ubuntu的相關(guān)API函數(shù)使用難度較大,需要安裝一些庫(kù),過(guò)程太過(guò)繁瑣。這里介紹一種比較簡(jiǎn)單的實(shí)現(xiàn)方法,即Qt的C++與SHELL結(jié)合使用來(lái)實(shí)現(xiàn)此功能:
- 在本project的目錄下,單獨(dú)存了一個(gè)SHELL文件。該SHELL中主要包含了一個(gè)圖片路徑變量和設(shè)置Ubuntu桌面背景的相關(guān)指令。
- 使用QFile設(shè)置更改SHELL文件中當(dāng)前的圖片路徑。
- 使用QProcess執(zhí)行此SHELL文件,更換壁紙。注:該SHELL文件的右鍵屬性權(quán)限中應(yīng)設(shè)置為“允許作為程序執(zhí)行文件”。
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 << "' ";//這么多空格是因?yàn)槊看温窂阶址L(zhǎng)度不等,保證能夠覆蓋。SHELL文件相應(yīng)位置也有空格(empty spaces)
file.close();
//調(diào)用執(zhí)行該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源代碼:
一款簡(jiǎn)約的壁紙?jiān)O(shè)置程序 https://github.com/polarbear0330/DeskWallPaper
本人聯(lián)系方式:362036379@sjtu.edu.cn,tfy.hi@163.com