PasswordBox.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. protected override void OnGotFocus(RoutedEventArgs e)
  120. {
  121. base.OnGotFocus(e);
  122. if(_textBox!=null)_textBox.Focus();
  123. }
  124. public System.Windows.Controls.PasswordBox ActualPasswordBox { get; set; }
  125. [DefaultValue("")]
  126. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  127. public string Password
  128. {
  129. get
  130. {
  131. if (ShowEyeButton && ShowPassword)
  132. {
  133. return _textBox.Text;
  134. }
  135. return ActualPasswordBox?.Password;
  136. }
  137. set
  138. {
  139. if (ActualPasswordBox == null)
  140. {
  141. _password = new SecureString();
  142. value ??= string.Empty;
  143. foreach (var item in value)
  144. _password.AppendChar(item);
  145. return;
  146. }
  147. if (Equals(ActualPasswordBox.Password, value)) return;
  148. ActualPasswordBox.Password = value;
  149. }
  150. }
  151. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  152. public SecureString SecurePassword => ActualPasswordBox?.SecurePassword;
  153. private static void OnShowPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  154. {
  155. var ctl = (PasswordBox) d;
  156. if (!ctl.ShowEyeButton) return;
  157. if ((bool) e.NewValue)
  158. {
  159. ctl._textBox.Text = ctl.ActualPasswordBox.Password;
  160. ctl._textBox.Select(string.IsNullOrEmpty(ctl._textBox.Text) ? 0 : ctl._textBox.Text.Length, 0);
  161. }
  162. else
  163. {
  164. ctl.ActualPasswordBox.Password = ctl._textBox.Text;
  165. ctl._textBox.Clear();
  166. }
  167. }
  168. public override void OnApplyTemplate()
  169. {
  170. if (ActualPasswordBox != null)
  171. ActualPasswordBox.PasswordChanged -= PasswordBox_PasswordChanged;
  172. if (_textBox != null)
  173. _textBox.TextChanged -= TextBox_TextChanged;
  174. base.OnApplyTemplate();
  175. ActualPasswordBox = GetTemplateChild(ElementPasswordBox) as System.Windows.Controls.PasswordBox;
  176. _textBox = GetTemplateChild(ElementTextBox) as System.Windows.Controls.TextBox;
  177. if(_textBox!=null)
  178. {
  179. _textBox.SetBinding(System.Windows.Controls.TextBox.MaxLengthProperty, new Binding(MaxLengthProperty.Name) { Source = this });
  180. _textBox.SetBinding(System.Windows.Controls.TextBox.SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
  181. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  182. _textBox.SetBinding(System.Windows.Controls.TextBox.SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
  183. #endif
  184. _textBox.SetBinding(System.Windows.Controls.TextBox.ForegroundProperty, new Binding(ForegroundProperty.Name) { Source = this });
  185. _textBox.SetBinding(System.Windows.Controls.TextBox.SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
  186. _textBox.SetBinding(System.Windows.Controls.TextBox.CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
  187. }
  188. if (ActualPasswordBox != null)
  189. {
  190. ActualPasswordBox.PasswordChanged += PasswordBox_PasswordChanged;
  191. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.MaxLengthProperty, new Binding(MaxLengthProperty.Name) { Source = this });
  192. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
  193. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  194. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
  195. #endif
  196. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
  197. ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
  198. if (_password is { Length: > 0 })
  199. {
  200. var valuePtr = IntPtr.Zero;
  201. try
  202. {
  203. valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
  204. ActualPasswordBox.Password = Marshal.PtrToStringUni(valuePtr) ?? throw new InvalidOperationException();
  205. }
  206. finally
  207. {
  208. Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  209. _password.Clear();
  210. }
  211. }
  212. }
  213. if (_textBox != null)
  214. {
  215. _textBox.TextChanged += TextBox_TextChanged;
  216. }
  217. }
  218. public void Paste()
  219. {
  220. ActualPasswordBox.Paste();
  221. if (ShowEyeButton && ShowPassword)
  222. {
  223. _textBox.Text = ActualPasswordBox.Password;
  224. }
  225. }
  226. public void SelectAll()
  227. {
  228. ActualPasswordBox.SelectAll();
  229. if (ShowEyeButton && ShowPassword)
  230. {
  231. _textBox.SelectAll();
  232. }
  233. }
  234. public void Clear()
  235. {
  236. ActualPasswordBox.Clear();
  237. _textBox.Clear();
  238. }
  239. private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
  240. {
  241. if (!IsSafeEnabled)
  242. {
  243. SetCurrentValue(UnsafePasswordProperty, ActualPasswordBox.Password);
  244. if (ShowPassword)
  245. {
  246. _textBox.Text = ActualPasswordBox.Password;
  247. }
  248. }
  249. }
  250. private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
  251. {
  252. if (!IsSafeEnabled && ShowPassword)
  253. {
  254. Password = _textBox.Text;
  255. SetCurrentValue(UnsafePasswordProperty, Password);
  256. }
  257. }
  258. }