PasswordBox.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. using System;
  2. using System.ComponentModel;
  3. using System.Runtime.InteropServices;
  4. using System.Security;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Controls.Primitives;
  8. using System.Windows.Data;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using HandyControl.Data;
  12. using HandyControl.Interactivity;
  13. namespace HandyControl.Controls;
  14. [TemplatePart(Name = ElementPasswordBox, Type = typeof(System.Windows.Controls.PasswordBox))]
  15. [TemplatePart(Name = ElementTextBox, Type = typeof(System.Windows.Controls.TextBox))]
  16. public class PasswordBox : Control
  17. {
  18. private const string ElementPasswordBox = "PART_PasswordBox";
  19. private const string ElementTextBox = "PART_TextBox";
  20. private SecureString _password;
  21. private System.Windows.Controls.TextBox _textBox;
  22. /// <summary>
  23. /// 掩码字符
  24. /// </summary>
  25. public static readonly DependencyProperty PasswordCharProperty =
  26. System.Windows.Controls.PasswordBox.PasswordCharProperty.AddOwner(typeof(PasswordBox),
  27. new FrameworkPropertyMetadata('●'));
  28. public char PasswordChar
  29. {
  30. get => (char) GetValue(PasswordCharProperty);
  31. set => SetValue(PasswordCharProperty, value);
  32. }
  33. public static readonly DependencyProperty ShowEyeButtonProperty = DependencyProperty.Register(
  34. nameof(ShowEyeButton), typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.FalseBox));
  35. public bool ShowEyeButton
  36. {
  37. get => (bool) GetValue(ShowEyeButtonProperty);
  38. set => SetValue(ShowEyeButtonProperty, ValueBoxes.BooleanBox(value));
  39. }
  40. public static readonly DependencyProperty ShowPasswordProperty = DependencyProperty.Register(
  41. nameof(ShowPassword), typeof(bool), typeof(PasswordBox),
  42. new PropertyMetadata(ValueBoxes.FalseBox, OnShowPasswordChanged));
  43. public bool ShowPassword
  44. {
  45. get => (bool) GetValue(ShowPasswordProperty);
  46. set => SetValue(ShowPasswordProperty, ValueBoxes.BooleanBox(value));
  47. }
  48. public static readonly DependencyProperty IsSafeEnabledProperty = DependencyProperty.Register(
  49. nameof(IsSafeEnabled), typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.TrueBox, OnIsSafeEnabledChanged));
  50. private static void OnIsSafeEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  51. {
  52. var p = (PasswordBox) d;
  53. p.SetCurrentValue(UnsafePasswordProperty, !(bool) e.NewValue ? p.Password : string.Empty);
  54. }
  55. public bool IsSafeEnabled
  56. {
  57. get => (bool) GetValue(IsSafeEnabledProperty);
  58. set => SetValue(IsSafeEnabledProperty, ValueBoxes.BooleanBox(value));
  59. }
  60. public static readonly DependencyProperty UnsafePasswordProperty = DependencyProperty.Register(
  61. nameof(UnsafePassword), typeof(string), typeof(PasswordBox), new FrameworkPropertyMetadata(default(string),
  62. FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnUnsafePasswordChanged));
  63. private static void OnUnsafePasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  64. {
  65. var p = (PasswordBox) d;
  66. if (!p.IsSafeEnabled)
  67. {
  68. p.Password = e.NewValue != null ? e.NewValue.ToString() : string.Empty;
  69. }
  70. }
  71. public string UnsafePassword
  72. {
  73. get => (string) GetValue(UnsafePasswordProperty);
  74. set => SetValue(UnsafePasswordProperty, value);
  75. }
  76. public static readonly DependencyProperty MaxLengthProperty =
  77. System.Windows.Controls.TextBox.MaxLengthProperty.AddOwner(typeof(PasswordBox));
  78. public int MaxLength
  79. {
  80. get => (int) GetValue(MaxLengthProperty);
  81. set => SetValue(MaxLengthProperty, value);
  82. }
  83. public static readonly DependencyProperty SelectionBrushProperty =
  84. TextBoxBase.SelectionBrushProperty.AddOwner(typeof(PasswordBox));
  85. public Brush SelectionBrush
  86. {
  87. get => (Brush) GetValue(SelectionBrushProperty);
  88. set => SetValue(SelectionBrushProperty, value);
  89. }
  90. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  91. public static readonly DependencyProperty SelectionTextBrushProperty =
  92. TextBoxBase.SelectionTextBrushProperty.AddOwner(typeof(PasswordBox));
  93. public Brush SelectionTextBrush
  94. {
  95. get => (Brush) GetValue(SelectionTextBrushProperty);
  96. set => SetValue(SelectionTextBrushProperty, value);
  97. }
  98. #endif
  99. public static readonly DependencyProperty SelectionOpacityProperty =
  100. TextBoxBase.SelectionOpacityProperty.AddOwner(typeof(PasswordBox));
  101. public double SelectionOpacity
  102. {
  103. get => (double) GetValue(SelectionOpacityProperty);
  104. set => SetValue(SelectionOpacityProperty, value);
  105. }
  106. public static readonly DependencyProperty CaretBrushProperty =
  107. TextBoxBase.CaretBrushProperty.AddOwner(typeof(PasswordBox));
  108. public Brush CaretBrush
  109. {
  110. get => (Brush) GetValue(CaretBrushProperty);
  111. set => SetValue(CaretBrushProperty, value);
  112. }
  113. #if !NET40
  114. public static readonly DependencyProperty IsSelectionActiveProperty =
  115. TextBoxBase.IsSelectionActiveProperty.AddOwner(typeof(PasswordBox));
  116. public bool IsSelectionActive => ActualPasswordBox != null && (bool) ActualPasswordBox.GetValue(IsSelectionActiveProperty);
  117. #endif
  118. public PasswordBox() => CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) => Clear()));
  119. public System.Windows.Controls.PasswordBox ActualPasswordBox { get; set; }
  120. [DefaultValue("")]
  121. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  122. public string Password
  123. {
  124. get
  125. {
  126. if (ShowEyeButton && ShowPassword)
  127. {
  128. return _textBox.Text;
  129. }
  130. return ActualPasswordBox?.Password;
  131. }
  132. set
  133. {
  134. if (ActualPasswordBox == null)
  135. {
  136. _password = new SecureString();
  137. value ??= string.Empty;
  138. foreach (var item in value)
  139. _password.AppendChar(item);
  140. return;
  141. }
  142. if (Equals(ActualPasswordBox.Password, value)) return;
  143. ActualPasswordBox.Password = value;
  144. }
  145. }
  146. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  147. public SecureString SecurePassword => ActualPasswordBox?.SecurePassword;
  148. private static void OnShowPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  149. {
  150. var ctl = (PasswordBox) d;
  151. if (!ctl.ShowEyeButton) return;
  152. if ((bool) e.NewValue)
  153. {
  154. ctl._textBox.Text = ctl.ActualPasswordBox.Password;
  155. ctl._textBox.Select(string.IsNullOrEmpty(ctl._textBox.Text) ? 0 : ctl._textBox.Text.Length, 0);
  156. }
  157. else
  158. {
  159. ctl.ActualPasswordBox.Password = ctl._textBox.Text;
  160. ctl._textBox.Clear();
  161. }
  162. }
  163. public override void OnApplyTemplate()
  164. {
  165. if (ActualPasswordBox != null)
  166. ActualPasswordBox.PasswordChanged -= PasswordBox_PasswordChanged;
  167. if (_textBox != null)
  168. _textBox.TextChanged -= TextBox_TextChanged;
  169. base.OnApplyTemplate();
  170. ActualPasswordBox = GetTemplateChild(ElementPasswordBox) as System.Windows.Controls.PasswordBox;
  171. _textBox = GetTemplateChild(ElementTextBox) as System.Windows.Controls.TextBox;
  172. if (ActualPasswordBox != null)
  173. {
  174. ActualPasswordBox.PasswordChanged += PasswordBox_PasswordChanged;
  175. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.MaxLengthProperty, new Binding(MaxLengthProperty.Name) { Source = this });
  176. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
  177. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  178. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
  179. #endif
  180. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
  181. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
  182. if (_password is { Length: > 0 })
  183. {
  184. var valuePtr = IntPtr.Zero;
  185. try
  186. {
  187. valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
  188. ActualPasswordBox.Password = Marshal.PtrToStringUni(valuePtr) ?? throw new InvalidOperationException();
  189. }
  190. finally
  191. {
  192. Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  193. _password.Clear();
  194. }
  195. }
  196. }
  197. if (_textBox != null)
  198. {
  199. _textBox.TextChanged += TextBox_TextChanged;
  200. }
  201. }
  202. public void Paste()
  203. {
  204. ActualPasswordBox.Paste();
  205. if (ShowEyeButton && ShowPassword)
  206. {
  207. _textBox.Text = ActualPasswordBox.Password;
  208. }
  209. }
  210. public void SelectAll()
  211. {
  212. ActualPasswordBox.SelectAll();
  213. if (ShowEyeButton && ShowPassword)
  214. {
  215. _textBox.SelectAll();
  216. }
  217. }
  218. public void Clear()
  219. {
  220. ActualPasswordBox.Clear();
  221. _textBox.Clear();
  222. }
  223. private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
  224. {
  225. if (!IsSafeEnabled)
  226. {
  227. SetCurrentValue(UnsafePasswordProperty, ActualPasswordBox.Password);
  228. if (ShowPassword)
  229. {
  230. _textBox.Text = ActualPasswordBox.Password;
  231. }
  232. }
  233. }
  234. private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
  235. {
  236. if (!IsSafeEnabled && ShowPassword)
  237. {
  238. Password = _textBox.Text;
  239. SetCurrentValue(UnsafePasswordProperty, Password);
  240. }
  241. }
  242. }