文章目录
- 运行效果
- 用到的运行库
- 代码实现
- 使用日志
- Win10 Flat风格
- XP风格
- 总结
运行效果
输入用户名和密码点击确定后获取到的信息:
用到的运行库
NuGet搜索安装即可
- Kang.ExtendMethod
- Kang.ExtendMethod.Log
https://gitee.com/haozekang/kang
- Vanara.PInvoke
https://github.com/dahall/Vanara/
代码实现
使用日志
readonly Logger logger = LogManager.GetCurrentClassLogger();
Win10 Flat风格
CredUI.CREDUI_INFO info = new CredUI.CREDUI_INFO();
info.pszCaptionText = "登录大伽";
info.pszMessageText = "欢迎使用大伽智能病理系统";
info.cbSize = Marshal.SizeOf(info);
uint pulAuthPackage = 0, ulInAuthBufferSize = 0, pulOutAuthBufferSize;
IntPtr pvInAuthBuffer = IntPtr.Zero, ppvOutAuthBuffer = IntPtr.Zero, pAuthBuffer = IntPtr.Zero;
bool isSave = false;
int maxUnSize = 50, maxPwSize = 50, maxDomSize = 50;
StringBuilder un = new StringBuilder(maxUnSize), pw = new StringBuilder(maxPwSize), dom = new StringBuilder(maxDomSize);
var error = CredUI.CredUIPromptForWindowsCredentials(info, Win32Error.NO_ERROR, ref pulAuthPackage, pvInAuthBuffer, ulInAuthBufferSize, out ppvOutAuthBuffer, out pulOutAuthBufferSize, ref isSave, CredUI.WindowsCredentialsDialogOptions.CREDUIWIN_GENERIC);
if (error == Win32Error.ERROR_CANCELLED)
{
logger.Debug($"{error}");
return;
}
if (error != Win32Error.ERROR_SUCCESS)
{
logger.Debug($"{error}");
return;
}
var flag = CredUI.CredUnPackAuthenticationBuffer(CredUI.CredPackFlags.CRED_PACK_GENERIC_CREDENTIALS, ppvOutAuthBuffer, (int)pulOutAuthBufferSize, un, ref maxUnSize, dom, ref maxDomSize, pw, ref maxPwSize);
if (un.ToString().IsBlank())
{
logger.Debug($"用户名不能为空!");
return;
}
if (pw.ToString().IsBlank())
{
logger.Debug($"密码不能为空!");
return;
}
if (!flag)
{
logger.Debug($"获取用户名及密码信息失败!");
return;
}
logger.Debug($"用户名:{un} 密码:{pw}");
XP风格
CredUI.CREDUI_INFO info = new CredUI.CREDUI_INFO();
info.pszCaptionText = "登录大伽";
info.pszMessageText = "欢迎使用大伽智能病理系统";
info.cbSize = Marshal.SizeOf(info);
IntPtr Reserved = IntPtr.Zero;
bool isSave = false;
int maxUnSize = 50, maxPwSize = 50;
StringBuilder un = new StringBuilder(maxUnSize), pw = new StringBuilder(maxPwSize);
var error = CredUI.CredUIPromptForCredentials(info, "www.dakapath.com/dakapath", Reserved, Win32Error.NO_ERROR, un, 10, pw, 10, ref isSave, CredUI.CredentialsDialogOptions.CREDUI_FLAGS_DEFAULT);
总结
- Win10风格的那个,取到的不是明文,是一个加密后的Pack,需要使用Windows自带的方法进行解密才可以拿到真实的用户名和密码,而XP风格的那个,是直接取到明文;
- 不想画登录界面的,对登录界面要求比较简单,又想自己的程序登录起来有点逼格的可以用Win10的那个(⊙o⊙)…;