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

标签 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);               

最佳答案

31 是 ERROR_GEN_FAILURE。如果您阅读 documentation ,有一条评论说:

I'm not sure why but it seems that CredUIPromptForWindowsCredentialsA always return ERROR_GEN_FAILURE (0x1E). Only Unicode version works.

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

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

此外,您正在将一个 char* 指针从临时 string 分配给 credui.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);

关于c++ - Windows API 函数 CredUIPromptForWindowsCredentials 也返回错误 31,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25885369/

相关文章:

c++ - 构造函数重载以接受任何函数

windows - 如何将键盘和鼠标输入发送到 Windows 登录屏幕?

delphi - 解决网络快捷方式

c++ - 创建附加到控制台但具有重定向标准 IO 句柄的进程

c++ - 在 OpenCV 2.4.9 中检测坏帧

c++ - 从线程更新进度条的最佳方法

c++ - 在其他函数或循环中构造 lambda 时是否存在性能问题?

winapi - 使用 DirectShow 的视频录制分辨率

c++ - 在Windows过程中获取滚动条ID

c++ - 如何修复程序上的错误以衡量性能