C++ Windows API函数CredUIPromptForWindowsCredentials也返回错误31

C++ Windows API函数CredUIPromptForWindowsCredentials也返回错误31,c++,winapi,C++,Winapi,当我使用函数CredUIPromptForWindowsCredentials显示windows安全身份验证对话框时,返回结果始终为31,并且该对话框不显示。 下面的代码有什么问题 CREDUI_INFO credui; credui.pszCaptionText = "Enter Network Password"; credui.pszMessageText = ("Enter your password to connect to: " + strDbPath).c_str();

当我使用函数CredUIPromptForWindowsCredentials显示windows安全身份验证对话框时,返回结果始终为31,并且该对话框不显示。
下面的代码有什么问题

CREDUI_INFO credui;  
credui.pszCaptionText = "Enter Network Password";  
credui.pszMessageText = ("Enter your password to connect to: " + strDbPath).c_str();  
credui.cbSize = sizeof(credui);  
credui.hbmBanner = nullptr;  
ULONG authPackage = 0;  
LPVOID outCredBuffer = nullptr;  
ULONG outCredSize = 0;  
BOOL save = false;  
int result = CredUIPromptForWindowsCredentials(&credui, 0, &authPackage, nullptr, 0, &outCredBuffer, &outCredSize, &save, 1);               

31是
错误\u GEN\u故障
。如果你读了,有一条评论说:

我不知道为什么,但creduipromptforWindowsCredentials似乎总是返回错误\u GEN\u FAILURE(0x1E)。只有Unicode版本可以工作

实际上,您正在调用Ansi版本的
CredUIPromptForWindowsCredentials()。请尝试调用Unicode版本

此外,您没有为
credui.hwndprent
字段赋值,也没有在填充前将
credui
清零,因此
hwndprent
具有不确定的值。您必须指定有效的
HWND
。如果没有,可以使用
NULL

另外,您正在将一个
char*
指针从一个临时
string
分配到
credui.pszMessageText
。在调用
CredUIPromptForWindowsCredentials()
之前,该
字符串超出范围并被销毁。您需要使用局部变量保存消息文本,直到使用它完成
CredUIPromptForWindowsCredentials()

试试这个:

std::wstring strDbPath = ...;
std::wstring strMsg = L"Enter your password to connect to: " + strDbPath;

CREDUI_INFOW credui = {};
credui.cbSize = sizeof(credui);  
credui.hwndParent = nullptr;
credui.pszMessageText = strMsg.c_str();
credui.pszCaptionText = L"Enter Network Password";
credui.hbmBanner = nullptr;

ULONG authPackage = 0;  
LPVOID outCredBuffer = nullptr;  
ULONG outCredSize = 0;  
BOOL save = false;  

int result = CredUIPromptForWindowsCredentialsW(&credui, 0, &authPackage, nullptr, 0, &outCredBuffer, &outCredSize, &save, 1);

该错误由设备驱动程序产生。您的机器似乎状态不好,可能是网络驱动程序堆栈出现故障。试试另一台机器,你说得对。只有此函数的Unicode版本有效。我不知道为什么。。