我正在尝试编写一个函数来获取 Windows 等效的 HOME。我的 C 技能生疏了,所以请不要介意我的示例代码无法编译。我试图在 Windows Vista 和更新版本上使用 SHGetKnownFolderPath,在 Server 2003 和更早版本上使用 SHGetFolderPath。因为我预计会遇到运行 Windows XP 的用户(因为它仍然是 Windows 的第一部署版本),所以我将避免在符号表中引用 SHGetKnownFolderPath(因为这会导致二进制文件甚至不会在 XP 上加载)。我从那里知道 LoadLibrary() shell32 和 GetProcAddress(),但至少可以说,我在处理函数指针方面的技能很糟糕。
当我编写难以处理的功能时,我将它们隔离到一个单独的示例文件中。到目前为止我遇到的坏例子是:
#include <windows.h>
#include <stdio.h>
// Pointerizing this Vista-and-later call for XP/2000 compat, etc.
typedef HRESULT (WINAPI* lpSHGetKnownFolderPath)(
REFKNOWNFOLDERID rfid,
DWORD dwFlags,
HANDLE hToken,
PWSTR *ppszPath
) lpSHGetKnownFolderPath;
int main(int argc, char *argv[])
{
// SHGet(Known)FolderPath() method.
HMODULE hndl_shell32;
lpSHGetKnownFolderPath pSHGetKnownFolderPath;
hndl_shell32 = LoadLibrary("shell32");
pSHGetKnownFolderPath = GetProcAddress(hndl_shell32, "SHGetKnownFolderPathW");
if(pSHGetKnownFolderPath != NULL) {
} else {
}
}
我的问题是:知道我做错了,我将如何正确地做这件事?我们将不胜感激关于如何在未来正确执行此操作的解释。谢谢。
最佳答案
这是一个小应用程序,展示了如何使用 LoadLibrary()
和 GetProcAddress()
以及评论中提供的建议:
#include <windows.h>
#include <stdio.h>
#include <shlobj.h>
/* The name of the function pointer type is
'lpSHGetKnownFolderPath', no need for
additional token after ')'. */
typedef HRESULT (WINAPI* lpSHGetKnownFolderPath)(
REFKNOWNFOLDERID rfid,
DWORD dwFlags,
HANDLE hToken,
PWSTR *ppszPath
);
int main()
{
HMODULE hndl_shell32;
lpSHGetKnownFolderPath pSHGetKnownFolderPath;
/* Always check the return value of LoadLibrary. */
hndl_shell32 = LoadLibrary("shell32");
if (NULL != hndl_shell32)
{
/* There is no 'SHGetKnownFolderPathW()'.
You need to cast return value of 'GetProcAddress()'. */
pSHGetKnownFolderPath = (lpSHGetKnownFolderPath)
GetProcAddress(hndl_shell32, "SHGetKnownFolderPath");
if(pSHGetKnownFolderPath != NULL)
{
PWSTR user_dir = 0;
if (SUCCEEDED(pSHGetKnownFolderPath(
FOLDERID_Profile,
0,
NULL,
&user_dir)))
{
/* Use 'user_dir' - remember to:
CoTaskMemFree(user_dir);
when no longer required.
*/
}
}
else
{
fprintf(stderr, "Failed to locate function: %d\n",
GetLastError());
}
/* Always match LoadLibrary with FreeLibrary.
If FreeLibrary() results in the shell32.dll
being unloaded 'pSHGetKnownFolderPath' is
no longer valid.
*/
FreeLibrary(hndl_shell32);
}
else
{
fprintf(stderr, "Failed to load shell32.dll: %d\n", GetLastError());
}
return 0;
}
这是在 Windows XP 上编译的。
Windows XP 上的输出:
Failed to locate function: 127
127
表示找不到指定的过程。
Windows Vista 上的输出:
C:\Users\admin
关于c++ - Windows 主页 - SHGet(已知)文件夹路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9463616/