Windows API函数CredUIPromptForWindowsCredentials也返回错误31

Windows API function CredUIPromptForWindowsCredentials also returns an error of 31

本文关键字:返回 错误 CredUIPromptForWindowsCredentials API 函数 Windows      更新时间:2023-10-16

当我使用函数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是ERROR_GEN_FAILURE。如果你阅读了文档,有一条评论说:

我不知道为什么,但似乎CredUIPromptForWindowsCredentialsA总是返回ERROR_GEN_FAILURE(0x1E)。只有Unicode版本有效。

事实上,您正在调用CredUIPromptForWindowsCredentials()的Ansi版本(通过将char*数据分配给CREDUI_INFO结构可以明显看出)。请尝试调用Unicode版本。

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

此外,您正在将char*指针从临时string分配给credui.pszMessageTextstring超出范围并在调用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);