使用SHGetSetSettings死活没用,后来在StackOverflow发现一份隐藏桌面图标的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copy this code from: https://stackoverflow.com/questions/53310374/how-to-hide-desktop-icons-with-windows-api-in-c

#include <ShlObj.h> // Shell API
#include <atlcomcli.h> // CComPtr & Co.
#include <string>
#include <iostream>
#include <system_error>
#include<Windows.h>


// Throw a std::system_error if the HRESULT indicates failure.
template< typename T >
void ThrowIfFailed(HRESULT hr, T&& msg)
{
if (FAILED(hr))
throw std::system_error{ hr, std::system_category(), std::forward<T>(msg) };
}

// RAII wrapper to initialize/uninitialize COM
struct CComInit
{
CComInit() { ThrowIfFailed(::CoInitialize(nullptr), "CoInitialize failed"); }
~CComInit() { ::CoUninitialize(); }
CComInit(CComInit const&) = delete;
CComInit& operator=(CComInit const&) = delete;
};

// Query an interface from the desktop shell view.
void FindDesktopFolderView(REFIID riid, void** ppv, std::string const& interfaceName)
{
CComPtr<IShellWindows> spShellWindows;
ThrowIfFailed(
spShellWindows.CoCreateInstance(CLSID_ShellWindows),
"Failed to create IShellWindows instance");

CComVariant vtLoc(CSIDL_DESKTOP);
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
ThrowIfFailed(
spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty, SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp),
"Failed to find desktop window");

CComQIPtr<IServiceProvider> spProv(spdisp);
if (!spProv)
ThrowIfFailed(E_NOINTERFACE, "Failed to get IServiceProvider interface for desktop");

CComPtr<IShellBrowser> spBrowser;
ThrowIfFailed(
spProv->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser)),
"Failed to get IShellBrowser for desktop");

CComPtr<IShellView> spView;
ThrowIfFailed(
spBrowser->QueryActiveShellView(&spView),
"Failed to query IShellView for desktop");

ThrowIfFailed(
spView->QueryInterface(riid, ppv),
"Could not query desktop IShellView for interface " + interfaceName);
}

void ToggleDesktopIcons()
{
CComPtr<IFolderView2> spView;
FindDesktopFolderView(IID_PPV_ARGS(&spView), "IFolderView2");

DWORD flags = 0;
ThrowIfFailed(
spView->GetCurrentFolderFlags(&flags),
"GetCurrentFolderFlags failed");
ThrowIfFailed(
spView->SetCurrentFolderFlags(FWF_NOICONS, flags ^ FWF_NOICONS),
"SetCurrentFolderFlags failed");
}

int wmain(int argc, wchar_t** argv)
{
try
{
CComInit init;

ToggleDesktopIcons();

std::cout << "Desktop icons have been toggled.\n";
}
catch (std::system_error const& e)
{
std::cout << "ERROR: " << e.what() << ", error code: " << e.code() << "\n";
return 1;
}

return 0;
}