Posted By

dzr_gregory on 10/15/10


Tagged

c keyboard WindowsForms


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Control keyboard key states anytime you want (Windows Forms)


 / Published in: C#
 

  1. using System.Windows.Forms;
  2.  
  3. namespace DistrictEditor.DataClasses
  4. {
  5.  
  6. /// <summary>
  7. /// Класс состояний клавиатуры
  8. /// </summary>
  9. public class Keyboard
  10. {
  11. /// <summary>
  12. /// Нажата ли клавиша Ctrl
  13. /// </summary>
  14. public bool IsCtrlPressed { get; private set; }
  15.  
  16. /// <summary>
  17. /// Нажата ли клавиша Alt
  18. /// </summary>
  19. public bool IsAltPressed { get; private set; }
  20.  
  21. /// <summary>
  22. /// Конструктор. Принимает экземпляр формы,
  23. /// на которой нам необходимо мониторить нажатия
  24. /// </summary>
  25. /// <param name="form">Экземпляр формы</param>
  26. public Keyboard(Form form)
  27. {
  28. if (form != null)
  29. {
  30. form.KeyDown += FormKeyDown;
  31. form.KeyUp += FormKeyUp;
  32. }
  33. }
  34.  
  35. /// <summary>
  36. /// Вызывается при отпускании клавиши
  37. /// </summary>
  38. /// <param name="sender"></param>
  39. /// <param name="e"></param>
  40. private void FormKeyUp(object sender, KeyEventArgs e)
  41. {
  42. IsCtrlPressed = IsCtrlPressed ? false : IsCtrlPressed;
  43. IsAltPressed = IsAltPressed ? false: IsAltPressed;
  44. }
  45.  
  46. /// <summary>
  47. /// Вызывается при нажатии клавиши
  48. /// </summary>
  49. /// <param name="sender"></param>
  50. /// <param name="e"></param>
  51. private void FormKeyDown(object sender, KeyEventArgs e)
  52. {
  53. IsCtrlPressed = e.Control;
  54. IsAltPressed = e.Alt;
  55. }
  56.  
  57. }
  58.  
  59. }

Report this snippet  

You need to login to post a comment.