windows 获取桌面路径的API函数:SHGetSpecialFolderPath
1.读取桌面路径的函数:
wstring GetDesktopPath()
{
TCHAR szPath[_MAX_PATH];
SHGetSpecialFolderPath(NULL,szPath,CSIDL_DESKTOP,0);
return wstring(szPath);
}
2.修改桌面路径
bool SetDeskTopPath(LPCTSTR szNewPath)
{
bool bResult = true ;
LPCTSTR lpKeyName = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
DWORD dwSize = wcslen(szNewPath) * sizeof(TCHAR);
LSTATUS ret =0;
HKEY hKey = 0 ;
try {
ret=(::RegOpenKeyExW(HKEY_CURRENT_USER,lpKeyName,0,KEY_READ,&hKey));
if(ret!=ERROR_SUCCESS){ throw L"错误:无法打开有关的hKEY"; }
LSTATUS ret = ::RegSetKeyValueW(HKEY_CURRENT_USER,lpKeyName,L"desktop",REG_SZ,szNewPath,dwSize);
if(ret !=ERROR_SUCCESS) {throw L"写入注册表错误!";}
}catch(LPCTSTR lpDescript)
{
std::cout<<L"错误消息"<<lpDescript<<endl;
bResult = false ;
}
::RegCloseKey(hKey) ;
return bResult ;
}
测试代码
//测试代码
//
#include "stdafx.h"
#include <iostream>
#include <shlobj.h>
using namespace std;
wstring GetDesktopPath();
bool SetDeskTopPath(LPCTSTR szNewPath) ;
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "chs");
TCHAR szPath[_MAX_PATH];
SHGetSpecialFolderPath(NULL,szPath,CSIDL_DESKTOP,0);
wstring str = GetDesktopPath();
std::wcout<<L"当前桌面:"<<str.c_str()<<std::endl;
SetDeskTopPath(L"D:\\我的新桌面");
wstring msg = L"勇敢牛牛不怕困难";
std::wcout<<msg.c_str()<<std::endl;
return 0;
}
wstring GetDesktopPath()
{
TCHAR szPath[_MAX_PATH];
SHGetSpecialFolderPath(NULL,szPath,CSIDL_DESKTOP,0);
return wstring(szPath);
}
bool SetDeskTopPath(LPCTSTR szNewPath)
{
bool bResult = true ;
LPCTSTR lpKeyName = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
DWORD dwSize = wcslen(szNewPath) * sizeof(TCHAR);
LSTATUS ret =0;
HKEY hKey = 0 ;
try {
ret=(::RegOpenKeyExW(HKEY_CURRENT_USER,lpKeyName,0,KEY_READ,&hKey));
if(ret!=ERROR_SUCCESS){ throw L"错误:无法打开有关的hKEY"; }
LSTATUS ret = ::RegSetKeyValueW(HKEY_CURRENT_USER,lpKeyName,L"desktop",REG_SZ,szNewPath,dwSize);
if(ret !=ERROR_SUCCESS) {throw L"写入注册表错误!";}
}catch(LPCTSTR lpDescript)
{
std::cout<<L"错误消息"<<lpDescript<<endl;
bResult = false ;
}
::RegCloseKey(hKey) ;
return bResult ;
}
————————————————
版权声明:本文为CSDN博主「衢州小风风」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/aasmfox/article/details/127960347