public static NetworkCredential GetCredentials(string caption, string message)
{
SafeNativeMethods.CREDUI_INFO uiInfo = new SafeNativeMethods.CREDUI_INFO();
uiInfo.cbSize = Marshal.SizeOf(uiInfo);
uiInfo.pszCaptionText = caption;
uiInfo.pszMessageText = message;
uint authPackage = 0;
IntPtr outCredBuffer = new IntPtr();
uint outCredSize;
bool save = false;
int result = SafeNativeMethods.CredUIPromptForWindowsCredentials(ref uiInfo, 0, ref authPackage,
IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, 0);
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 (SafeNativeMethods.CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
{
SafeNativeMethods.CoTaskMemFree(outCredBuffer);
return new NetworkCredential()
{
UserName = usernameBuf.ToString(),
Password = passwordBuf.ToString(),
Domain = domainBuf.ToString()
};
}
}
return null;
}