PassWordKeyBoard.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. namespace Muchinfo.WPF.Controls.Keyboard
  10. {
  11. public class PassWordKeyBoard : Window
  12. {
  13. #region fields
  14. private static Control _currentControl;
  15. private const double HeightTouchKeyboard = 190;
  16. private static Window _instanceObject;
  17. private static Brush _previousTextBoxBackgroundBrush = null;
  18. private static Brush _previousTextBoxBorderBrush = null;
  19. private static Thickness _previousTextBoxBorderThickness;
  20. private static double _widthTouchKeyboard = 400;
  21. #endregion
  22. #region DependencyProperty
  23. /// <summary>
  24. /// 特殊数字字符
  25. /// </summary>
  26. public ObservableCollection<KeyModel> SpecialNumberChars
  27. {
  28. get { return (ObservableCollection<KeyModel>)GetValue(SpecialNumberCharsProperty); }
  29. set { SetValue(SpecialNumberCharsProperty, value); }
  30. }
  31. // Using a DependencyProperty as the backing store for SpecialChars. This enables animation, styling, binding, etc...
  32. public static readonly DependencyProperty SpecialNumberCharsProperty =
  33. DependencyProperty.Register("SpecialNumberChars", typeof(ObservableCollection<KeyModel>), typeof(PassWordKeyBoard), new PropertyMetadata(new ObservableCollection<KeyModel>()));
  34. /// <summary>
  35. /// 英文字母
  36. /// </summary>
  37. public ObservableCollection<KeyModel> EnglishChars
  38. {
  39. get { return (ObservableCollection<KeyModel>)GetValue(EnglishCharsProperty); }
  40. set { SetValue(EnglishCharsProperty, value); }
  41. }
  42. // Using a DependencyProperty as the backing store for EnglishChars. This enables animation, styling, binding, etc...
  43. public static readonly DependencyProperty EnglishCharsProperty =
  44. DependencyProperty.Register("EnglishChars", typeof(ObservableCollection<KeyModel>), typeof(PassWordKeyBoard), new PropertyMetadata(new ObservableCollection<KeyModel>()));
  45. /// <summary>
  46. /// 用户按下回车
  47. /// </summary>
  48. public ICommand EnterCommand
  49. {
  50. get { return (ICommand)GetValue(EnterCommandProperty); }
  51. set { SetValue(EnterCommandProperty, value); }
  52. }
  53. // Using a DependencyProperty as the backing store for EnterCommand. This enables animation, styling, binding, etc...
  54. public static readonly DependencyProperty EnterCommandProperty =
  55. DependencyProperty.Register("EnterCommand", typeof(ICommand), typeof(PassWordKeyBoard), new PropertyMetadata(null));
  56. /// <summary>
  57. /// 用户按下空格
  58. /// </summary>
  59. public ICommand SpaceCommand
  60. {
  61. get { return (ICommand)GetValue(SpaceCommandProperty); }
  62. set { SetValue(SpaceCommandProperty, value); }
  63. }
  64. // Using a DependencyProperty as the backing store for SpaceCommand. This enables animation, styling, binding, etc...
  65. public static readonly DependencyProperty SpaceCommandProperty =
  66. DependencyProperty.Register("SpaceCommand", typeof(ICommand), typeof(PassWordKeyBoard), new PropertyMetadata(null));
  67. /// <summary>
  68. /// 用户按下退格键
  69. /// </summary>
  70. public ICommand BackSpaceCommand
  71. {
  72. get { return (ICommand)GetValue(BackSpaceCommandProperty); }
  73. set { SetValue(BackSpaceCommandProperty, value); }
  74. }
  75. // Using a DependencyProperty as the backing store for BackSpaceCommand. This enables animation, styling, binding, etc...
  76. public static readonly DependencyProperty BackSpaceCommandProperty =
  77. DependencyProperty.Register("BackSpaceCommand", typeof(ICommand), typeof(PassWordKeyBoard), new PropertyMetadata(null));
  78. /// <summary>
  79. /// 用户按下清除键
  80. /// </summary>
  81. public ICommand ClearCommand
  82. {
  83. get { return (ICommand)GetValue(ClearCommandProperty); }
  84. set { SetValue(ClearCommandProperty, value); }
  85. }
  86. // Using a DependencyProperty as the backing store for ClearCommand. This enables animation, styling, binding, etc...
  87. public static readonly DependencyProperty ClearCommandProperty =
  88. DependencyProperty.Register("ClearCommand", typeof(ICommand), typeof(PassWordKeyBoard), new PropertyMetadata(null));
  89. #endregion
  90. public PassWordKeyBoard()
  91. {
  92. InitCharCommand();
  93. SetCommandBinding();
  94. this.Height = HeightTouchKeyboard;
  95. this.Width = _widthTouchKeyboard;
  96. }
  97. static PassWordKeyBoard()
  98. {
  99. DefaultStyleKeyProperty.OverrideMetadata(typeof(PassWordKeyBoard), new FrameworkPropertyMetadata(typeof(PassWordKeyBoard)));
  100. }
  101. #region Properties
  102. public static string TouchScreenText
  103. {
  104. get
  105. {
  106. if (_currentControl is TextBox)
  107. {
  108. return ((TextBox)_currentControl).Text;
  109. }
  110. else if (_currentControl is PasswordBox)
  111. {
  112. return ((PasswordBox)_currentControl).Password;
  113. }
  114. else return "";
  115. }
  116. set
  117. {
  118. if (_currentControl is TextBox)
  119. {
  120. ((TextBox)_currentControl).Text = value;
  121. }
  122. else if (_currentControl is PasswordBox)
  123. {
  124. ((PasswordBox)_currentControl).Password = value;
  125. }
  126. }
  127. }
  128. public static double WidthTouchKeyboard
  129. {
  130. get { return _widthTouchKeyboard; }
  131. set { _widthTouchKeyboard = value; }
  132. }
  133. #endregion Properties
  134. #region Methods
  135. /// <summary>
  136. /// 初始化字符列表
  137. /// </summary>
  138. private void InitCharCommand()
  139. {
  140. //32为空格,密码不使用空格
  141. List<KeyModel> keyModelList = new List<KeyModel>();
  142. for (byte ch = 33; ch < 127; ch++)
  143. {
  144. keyModelList.Add(new KeyModel()
  145. {
  146. KeyChar = Convert.ToChar(ch),
  147. CharValue = ch,
  148. KeyRoutedCommand = new RoutedCommand()
  149. });
  150. }
  151. List<KeyModel> numberChars = new List<KeyModel>
  152. (keyModelList.Where(ch => ch.CharValue >= 48 && ch.CharValue <= 57));
  153. var englishChars = new List<KeyModel>
  154. (keyModelList.Where(ch => ch.CharValue >= 65 && ch.CharValue <= 90)); //取
  155. englishChars = RandomList(englishChars);// 打乱排序
  156. EnglishChars = new ObservableCollection<KeyModel>(englishChars);
  157. if (numberChars.Any() && EnglishChars.Any())
  158. {
  159. List<KeyModel> specialChars = new List<KeyModel>(keyModelList.Where(ch =>
  160. !numberChars.Contains(ch) && !EnglishChars.Contains(ch) && (ch.CharValue < 97 || ch.CharValue > 122)
  161. ));
  162. numberChars = RandomList(numberChars);// 打乱排序
  163. specialChars = RandomList(specialChars);
  164. specialChars.AddRange(numberChars);
  165. SpecialNumberChars = new ObservableCollection<KeyModel>(specialChars);
  166. }
  167. }
  168. //点按钮执行的命令
  169. private void RunCommand(object sender, ExecutedRoutedEventArgs e)
  170. {
  171. if (e.Parameter == null) return;
  172. PassWordKeyBoard.TouchScreenText += e.Parameter.ToString();
  173. }
  174. /// <summary>
  175. /// 注册字符命令
  176. /// </summary>
  177. private void SetCommandBinding()
  178. {
  179. //注册特殊字符\数字命令
  180. foreach (KeyModel keyModel in SpecialNumberChars)
  181. {
  182. var commandBinding = new CommandBinding(keyModel.KeyRoutedCommand, RunCommand);
  183. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), commandBinding);
  184. }
  185. //注册字母命令
  186. foreach (KeyModel englishChar in EnglishChars)
  187. {
  188. var englishBinding = new CommandBinding(englishChar.KeyRoutedCommand, RunCommand);
  189. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), englishBinding);
  190. }
  191. //回车
  192. EnterCommand = new RoutedCommand();
  193. var enterBinding = new CommandBinding(EnterCommand, ControlRunCommand);
  194. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), enterBinding);
  195. //空格
  196. SpaceCommand = new RoutedCommand();
  197. var spaceBinding = new CommandBinding(SpaceCommand, ControlRunCommand);
  198. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), spaceBinding);
  199. //退格
  200. BackSpaceCommand = new RoutedCommand();
  201. var backSpacBinding = new CommandBinding(BackSpaceCommand, ControlRunCommand);
  202. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), backSpacBinding);
  203. //清除
  204. ClearCommand = new RoutedCommand();
  205. var clearBinding = new CommandBinding(ClearCommand, ControlRunCommand);
  206. CommandManager.RegisterClassCommandBinding(typeof(PassWordKeyBoard), clearBinding);
  207. }
  208. //执行控制命令
  209. private void ControlRunCommand(object sender, ExecutedRoutedEventArgs e)
  210. {
  211. if (e.Command == EnterCommand)
  212. {
  213. if (_instanceObject != null)
  214. {
  215. _instanceObject.Close();
  216. _instanceObject = null;
  217. }
  218. _currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
  219. }
  220. else if (e.Command == SpaceCommand)
  221. {
  222. PassWordKeyBoard.TouchScreenText += " ";
  223. }
  224. else if (e.Command == BackSpaceCommand)
  225. {
  226. if (!string.IsNullOrEmpty(PassWordKeyBoard.TouchScreenText))
  227. {
  228. PassWordKeyBoard.TouchScreenText = PassWordKeyBoard.TouchScreenText.Substring(0, PassWordKeyBoard.TouchScreenText.Length - 1);
  229. }
  230. }
  231. else if (e.Command == ClearCommand)
  232. {
  233. PassWordKeyBoard.TouchScreenText = "";
  234. }
  235. }
  236. public static void Dispose()
  237. {
  238. _currentControl = null;
  239. _previousTextBoxBackgroundBrush = null;
  240. _previousTextBoxBorderBrush = null;
  241. if (_instanceObject != null)
  242. {
  243. _instanceObject.Close();
  244. _instanceObject = null;
  245. }
  246. }
  247. public static readonly DependencyProperty TouchScreenKeyboardProperty =
  248. DependencyProperty.RegisterAttached("TouchScreenKeyboard", typeof(bool), typeof(PassWordKeyBoard), new UIPropertyMetadata(default(bool), TouchScreenKeyboardPropertyChanged));
  249. public static bool GetTouchScreenKeyboard(DependencyObject obj)
  250. {
  251. return (bool)obj.GetValue(TouchScreenKeyboardProperty);
  252. }
  253. public static void SetTouchScreenKeyboard(DependencyObject obj, bool value)
  254. {
  255. obj.SetValue(TouchScreenKeyboardProperty, value);
  256. }
  257. static void OnGotFocus(object sender, RoutedEventArgs e)
  258. {
  259. var host = sender as Control;
  260. if (host != null)
  261. {
  262. _previousTextBoxBackgroundBrush = host.Background;
  263. _previousTextBoxBorderBrush = host.BorderBrush;
  264. _previousTextBoxBorderThickness = host.BorderThickness;
  265. //host.Background = Brushes.Yellow;
  266. //host.BorderBrush = Brushes.Red;
  267. host.BorderThickness = new Thickness(host.BorderThickness.Bottom+1);
  268. host.BorderThickness = new Thickness(2);
  269. _currentControl = host;
  270. if (_instanceObject == null)
  271. {
  272. FrameworkElement ct = host;
  273. while (true)
  274. {
  275. if (ct is Window)
  276. {
  277. ((Window)ct).Activated += new EventHandler(TouchScreenKeyboard_Activated);
  278. ((Window)ct).Deactivated += new EventHandler(TouchScreenKeyboard_Deactivated);
  279. break;
  280. }
  281. ct = (FrameworkElement)ct.Parent;
  282. }
  283. _instanceObject = new PassWordKeyBoard();
  284. _instanceObject.AllowsTransparency = true;
  285. _instanceObject.WindowStyle = WindowStyle.None;
  286. _instanceObject.ShowInTaskbar = false;
  287. _instanceObject.ShowInTaskbar = false;
  288. _instanceObject.Topmost = true;
  289. SyncChild();
  290. // host.LayoutUpdated += new EventHandler(tb_LayoutUpdated);
  291. }
  292. }
  293. }
  294. static void OnLostFocus(object sender, RoutedEventArgs e)
  295. {
  296. Control host = sender as Control;
  297. host.Background = _previousTextBoxBackgroundBrush;
  298. host.BorderBrush = _previousTextBoxBorderBrush;
  299. host.BorderThickness = _previousTextBoxBorderThickness;
  300. if (_instanceObject != null)
  301. {
  302. _instanceObject.Close();
  303. _instanceObject = null;
  304. }
  305. SetTouchScreenKeyboard(host, false);
  306. //设置只有使用按键时才打开键盘。
  307. host.GotFocus -= OnGotFocus;
  308. host.LostFocus -= OnLostFocus;
  309. }
  310. private static void OnUnloaded(object sender, RoutedEventArgs e)
  311. {
  312. if (_instanceObject != null)
  313. {
  314. _instanceObject.Close();
  315. }
  316. }
  317. /// <summary>
  318. /// Syncs the child.
  319. /// </summary>
  320. private static void SyncChild()
  321. {
  322. if (_currentControl != null && _instanceObject != null)
  323. {
  324. Point virtualpoint = new Point(0, _currentControl.ActualHeight + 3);
  325. Point Actualpoint = _currentControl.PointToScreen(virtualpoint);
  326. if (WidthTouchKeyboard + Actualpoint.X > SystemParameters.VirtualScreenWidth)
  327. {
  328. double difference = WidthTouchKeyboard + Actualpoint.X - SystemParameters.VirtualScreenWidth;
  329. _instanceObject.Left = Actualpoint.X - difference;
  330. }
  331. else if (!(Actualpoint.X > 1))
  332. {
  333. _instanceObject.Left = 1;
  334. }
  335. else
  336. {
  337. _instanceObject.Left = Actualpoint.X;
  338. }
  339. _instanceObject.Top = Actualpoint.Y;
  340. _instanceObject.Show();
  341. }
  342. }
  343. static void TouchScreenKeyboardPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
  344. {
  345. FrameworkElement host = sender as FrameworkElement;
  346. if (host != null && e.NewValue.Equals(true))
  347. {
  348. host.GotFocus += new RoutedEventHandler(OnGotFocus);
  349. host.Unloaded += OnUnloaded;
  350. host.LostFocus += new RoutedEventHandler(OnLostFocus);
  351. }
  352. }
  353. static void TouchScreenKeyboard_Activated(object sender, EventArgs e)
  354. {
  355. if (_instanceObject != null)
  356. {
  357. _instanceObject.Topmost = true;
  358. }
  359. }
  360. static void TouchScreenKeyboard_Deactivated(object sender, EventArgs e)
  361. {
  362. if (_instanceObject != null)
  363. {
  364. _instanceObject.Topmost = false;
  365. }
  366. }
  367. /// <summary>
  368. /// 随机打乱一组数据。
  369. /// </summary>
  370. /// <typeparam name="T">泛型T</typeparam>
  371. /// <param name="Tlist">T列表</param>
  372. /// <returns></returns>
  373. private List<T> RandomList<T>(List<T> Tlist)
  374. {
  375. if (Tlist == null || Tlist.Count == 0) return null;
  376. Random random = new Random();
  377. ;
  378. T Temp;
  379. for (int i = Tlist.Count - 1; i > 0; i--)
  380. {
  381. int j = random.Next(i);
  382. Temp = Tlist[i];
  383. Tlist[i] = Tlist[j];
  384. Tlist[j] = Temp;
  385. }
  386. return Tlist;
  387. }
  388. #endregion Methods
  389. }
  390. }