Windows API函数CredUIPromptForWindowsCredentials也返回错误31

Den*_*nis 4 c++ winapi

当我使用函数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);               
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

31是ERROR_GEN_FAILURE。如果您阅读该文档,则会有一条注释:

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

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

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

此外,您正在分配char*从临时指针stringcredui.pszMessageText。那string超出范围并在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);
Run Code Online (Sandbox Code Playgroud)