gpt4 book ai didi

c# - 在 C# 中为 Windows Vista/7 显示身份验证对话框

转载 作者:可可西里 更新时间:2023-11-01 08:58:39 28 4
gpt4 key购买 nike

我想从用户那里获取网络登录凭据。

我正在使用 .NET 3.5 和 C#。到目前为止,我使用的是 CredUIPromptForCredentials 调用(可以找到关于如何使用它的非常有用的链接 here )

我的问题是 CredUIPromptForCredentials API 调用显示旧的 windows 2000/XP 凭据对话框而不是新的 Vista/7。

我在 msdn 上读到我应该使用 CredUIPromptForWindowsCredentials 功能。

有人可以发布一个如何在 C# 中使用它的示例吗?我还需要能够获取输入的凭据。

最佳答案

我设法实现了一个适合我的解决方案。

这是源代码:

    [DllImport("ole32.dll")]
public static extern void CoTaskMemFree(IntPtr ptr);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}


[DllImport("credui.dll", CharSet = CharSet.Auto)]
private static extern bool CredUnPackAuthenticationBuffer(int dwFlags,
IntPtr pAuthBuffer,
uint cbAuthBuffer,
StringBuilder pszUserName,
ref int pcchMaxUserName,
StringBuilder pszDomainName,
ref int pcchMaxDomainame,
StringBuilder pszPassword,
ref int pcchMaxPassword);

[DllImport("credui.dll", CharSet = CharSet.Auto)]
private static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere,
int authError,
ref uint authPackage,
IntPtr InAuthBuffer,
uint InAuthBufferSize,
out IntPtr refOutAuthBuffer,
out uint refOutAuthBufferSize,
ref bool fSave,
int flags);



public static void GetCredentialsVistaAndUp(string serverName, out NetworkCredential networkCredential)
{
CREDUI_INFO credui = new CREDUI_INFO();
credui.pszCaptionText = "Please enter the credentails for " + serverName;
credui.pszMessageText = "DisplayedMessage";
credui.cbSize = Marshal.SizeOf(credui);
uint authPackage = 0;
IntPtr outCredBuffer = new IntPtr();
uint outCredSize;
bool save = false;
int result = CredUIPromptForWindowsCredentials(ref credui,
0,
ref authPackage,
IntPtr.Zero,
0,
out outCredBuffer,
out outCredSize,
ref save,
1 /* Generic */);

var usernameBuf = new StringBuilder(100);
var passwordBuf = new StringBuilder(100);
var domainBuf = new StringBuilder(100);

int maxUserName = 100;
int maxDomain = 100;
int maxPassword = 100;
if (result == 0)
{
if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
{
//TODO: ms documentation says we should call this but i can't get it to work
//SecureZeroMem(outCredBuffer, outCredSize);

//clear the memory allocated by CredUIPromptForWindowsCredentials
CoTaskMemFree(outCredBuffer);
networkCredential = new NetworkCredential()
{
UserName = usernameBuf.ToString(),
Password = passwordBuf.ToString(),
Domain = domainBuf.ToString()
};
return;
}
}

networkCredential = null;
}

我仍然需要弄清楚细节,例如如何记住最后输入的凭据等...

但主要部分有效。

关于c# - 在 C# 中为 Windows Vista/7 显示身份验证对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4134882/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com