Rx Keyboard Events in WP7


/ Published in: C#
Save to your folder(s)

Toying around with Rx in WP7, thought this was interesting...


Copy this code and paste it in your HTML
  1. // Class private var
  2. private ISubject<KeyboardState> _KeyboardStates;
  3.  
  4. // Setup in ctor
  5. _KeyboardStates = new ReplaySubject<KeyboardState>();
  6.  
  7. // In the update event
  8. _KeyboardStates.OnNext(Keyboard.GetState());
  9.  
  10. // Func to compare key states (there is probably a better solution for this)
  11. public static Func<KeyboardState, string> KeyStateComparer
  12. {
  13. get
  14. {
  15. return (ks) =>
  16. {
  17. var sb = new StringBuilder();
  18. ks.GetPressedKeys().ToList().ForEach((key) => sb.Append(key.ToString()));
  19. return sb.ToString();
  20. };
  21. }
  22. }
  23.  
  24. // Extension method to make it easy to append this overload of distinct
  25. public static IObservable<KeyboardState> DistinctUntilChanged(this IObservable<KeyboardState> target)
  26. {
  27. return target.DistinctUntilChanged(KeyStateComparer);
  28. }
  29.  
  30. // Now that the update event is feeding the _KeyboardStates Observable we can...
  31.  
  32. var keyPressed = from ks in _KeyboardStates.DistinctUntilChanged()
  33. select ks;
  34.  
  35. var keyDowns = from ks in keyPressed
  36. .Zip(keyPressed.Skip(1), (prev, cur) =>
  37. {
  38. return from k in cur.GetPressedKeys()
  39. where !prev.GetPressedKeys().Contains(k)
  40. select k;
  41. })
  42. select ks;
  43.  
  44. var keyUps = from ks in keyPressed
  45. .Zip(keyPressed.Skip(1), (prev, cur) =>
  46. {
  47. return from k in prev.GetPressedKeys()
  48. where !cur.GetPressedKeys().Contains(k)
  49. select k;
  50. })
  51. select ks;
  52.  
  53. // And with those observables we can...
  54.  
  55. keyPressed.Subscribe((keys) =>
  56. {
  57. if (keys.GetPressedKeys().Length > 0)
  58. {
  59. var sb = new StringBuilder();
  60. keys.GetPressedKeys().ToList().ForEach((key) => sb.Append(key.ToString()));
  61. Debug.WriteLine("Keys: " + sb.ToString());
  62. }
  63. });
  64.  
  65. keyDowns.Subscribe((keys) =>
  66. {
  67. foreach (var key in keys)
  68. {
  69. Debug.WriteLine("Key down: " + key);
  70. }
  71. });
  72.  
  73. keyUps.Subscribe((keys) =>
  74. {
  75. foreach (var key in keys)
  76. {
  77. Debug.WriteLine("Key up: " + key);
  78. }
  79. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.