如何从C++控制台应用程序中使用shell32.dll

How to use shell32.dll from C++ console application

本文关键字:shell32 dll 应用程序 C++ 控制台      更新时间:2023-10-16

我需要做的是获得ApplicationData路径,我在谷歌上发现有一个叫做的函数

HRESULT SHGetFolderPath(
  __in   HWND hwndOwner,
  __in   int nFolder,
  __in   HANDLE hToken,
  __in   DWORD dwFlags,
  __out  LPTSTR pszPath
);

但它存在于shell32.dll中在C#中,我会做一些类似的事情

[DllImport]
static extern HRESULT SHGetFolderPath() and so on.

我需要在C++控制台应用程序中做些什么才能调用这个API?也许,我可以使用LoadLibrary()?但正确的方法是什么?

我可以以某种方式静态链接这个dll作为我的exe的一部分吗?我正在使用Visual Studio 2010。

您需要#include shlobj.h并链接到shell32.lib

#include "stdafx.h"
#include <windows.h>
#include <shlobj.h>
#include <assert.h>
#pragma comment(lib, "shell32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
    TCHAR path[MAX_PATH];
    HRESULT hr = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path);
    assert(SUCCEEDED(hr));
    // etc..
    return 0;
}

#pragma注释负责将其告知链接器。

#include <Shlobj.h>#pragma comment(lib,"Shell32.lib")应该可以工作。