internal partial class CredentialsFormHelper : Form { public string Username { get; set; } public string Password { get; set; } public bool Successful { get; set; } public CredentialsFormHelper() { InitializeComponent(); } public bool GetCredentials(string serverName, IntPtr hwndParent, out NetworkCredential? networkCredential) { bool save = false; int errorcode = 0; uint dialogReturn; uint authPackage = 0; IntPtr outCredBuffer = new IntPtr(); uint outCredSize; CredentialsPromptHelper.CREDUI_INFO credui = new(); credui.cbSize = Marshal.SizeOf(credui); credui.pszCaptionText = "Login"; credui.pszMessageText = "Bitte geben Sie ihre Logindaten ein!"; credui.hwndParent = hwndParent; dialogReturn = CredentialsPromptHelper.CredUIPromptForWindowsCredentials(ref credui, errorcode, ref authPackage, IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, CredentialsPromptHelper.PromptForWindowsCredentialsFlags.CREDUIWIN_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 (dialogReturn == 0) { if (CredentialsPromptHelper.CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword)) { CredentialsPromptHelper.CoTaskMemFree(outCredBuffer); networkCredential = new NetworkCredential() { UserName = usernameBuf.ToString(), Password = passwordBuf.ToString(), Domain = domainBuf.ToString() }; return true; } } networkCredential = null; return false; } public static string SecureStringToString(SecureString value) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value); string? unicodeString = Marshal.PtrToStringUni(valuePtr); byte[] bytes = Encoding.Unicode.GetBytes(unicodeString); bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytes); return Encoding.UTF8.GetString(bytes); } catch (Exception ex) { MessageBox.Show(ex.Message); return String.Empty; } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } private void CredentialsFormHelper_Load(object sender, EventArgs e) { this.Visible = false; if (GetCredentials("", this.Handle, out NetworkCredential? networkCredential)) { this.Username = networkCredential.UserName; this.Password = SecureStringToString(networkCredential.SecurePassword); this.Successful = true; } else this.Successful = false; this.Close(); } }