C#,Delphi,Oracle,MSSQL 개발자블로그

C# 마우스와 키보드 본문

Programming/C#

C# 마우스와 키보드

19760323 2017. 8. 10. 20:38

마우스와 키보드

키보드는 가장 오래된 입력장치 중 하나이며, 마우스는 GUI 환경에서 꼭 필요한 필수 입력장치이다. 이 두 장치에 대한 정보도 처리하여 입력되는 값이나 위치를 프로그램에 반영할 수 있다.

키보드

키의 입력에는 4종류가 있다

  • 문자키 : 문자, 숫자, Space, BackSpace, Esc
  • 비문자키 : 방향키, 펑션키, 삽입 등의 문자입력과 연관없는 값
  • 토글키 : Caps Lock, Num Lock, Scroll Lock, Insert 등
  • 쉬프트키 : Shift, Alt, Ctrl 등 조합되는 키

Control 클래스를 상속받은 하위 클래스에서 키에 대한 대표적인 이벤트는 KeyDownKeyUp이 있다. KeyDown은 키보드가 눌려져서 있는 상태에 발생하고,  KeyUp은 눌려진 키를 다시 놓으면 발생한다.

키보드 관련 이벤트 핸들러의 매개변수에 KeyEventArgs클래스 인스턴스가 필요하고 여기에는 다음과 같은 속성이 존재한다.

  • Alt: Alt키가 눌려졌는지 여부 [bool]
  • Control: Ctrl키가 눌려졌는지 여부 [bool]
  • Handled: 이벤트 처리 여부 [bool]
  • KeyCode: 키보드 코드 반환 [Keys]
  • KeyData: 누른 키에 대한 키코드와 동시에 누른 Shift 키들에 대한 조합 [Key]
  • KeyValue: KeyCode 속성 정수값 [int]
  • Modifiers: 하나이상의 보조키 플래그 [Keys]
  • Shift: Shift키 눌려졌는지 여부 [bool]
  • SuppressKeyPress: 키 이벤트 내부 컨트롤에 전달할지 여부 [bool]

다음으로 KeyPress메서드가 있다. 이는 컨트롤에 포커스가 있을때 키를 누르면 발생하는 이벤트이다. 이벤트 발생순서는 KeyDown → KeyPress → KeyUp 순으로 발생한다. KeyPress이벤트 핸들러의 메서드의 매개변수는 KeyPressEventArgs클래스 인스턴스이다.

  • KeyChar : 유니코드 문자 [char]
  • Handled : KeyPress 이벤트가 처리되었는지 여부 [bool]

예제를 보도록 하자. 이 예제를 실습하면 키보드에 대한 이해를 쉽게 할 수 있다.

  1. string strData = "";
    static void Main(string[] args)  {
        Application.Run(new KeyTest());
    }
    public KeyTest()  {
        this.Text = "문자 입력 예제";
        this.BackColor = Color.Black;
        this.ForeColor = Color.White;
        this.Size = new Size(500, 600);
        this.KeyDown += new KeyEventHandler(KeyTest_KeyDown);
        this.KeyPress += new KeyPressEventHandler(KeyTest_KeyPress);
        this.KeyUp += new KeyEventHandler(KeyTest_KeyUp);

    }
    private void KeyTest_KeyDown(object sender, KeyEventArgs e)  {
        strData += String.Format("\n ① {0} KeyDown", e.KeyCode);
        Invalidate();
    }
    private void KeyTest_KeyUp(object sender, KeyEventArgs e)  {
        strData += String.Format("\n ② {0} KeyUp", e.KeyCode);
        Invalidate();
    }
    private void KeyTest_KeyPress(object sender, KeyPressEventArgs e)  {
        strData += String.Format("\n ③ {0} KeyPress", e.KeyChar);
        Invalidate();
    }
    protected override void OnPaint(PaintEventArgs e)  {
        Graphics g = e.Graphics;
        g.DrawString(strData, new Font("맑은 고딕", 10, FontStyle.Bold), Brushes.White, 20, 30);           
        base.OnPaint(e);
    }

 

KeyTest.gif

마우스

마우스는 GUI(Graphic User Interface)에서 가장 기본이 되는 입력장치이다. 첫번째로 마우스에 대한 등록 정보를 출력하는 간단한 예제를 먼저 보도록 하자.

  1. 11 public partial class Form1 : Form

    12 {

    13     public Form1()

    14    {

    15       InitializeComponent();

    16    }

    17

    18    private void btn_MouseCheck_Click(object sender, EventArgs e)

    19    {

    20         String strMI = String.Format("휠 마우스 설치 : {0} \n 마우스 버튼 개수 : {1} \n " +

    21                  "버튼스왑 : {2} \n 마우스속도 : {3} \n" +

    22                  "휠 델타값 : {4} \n 휠 라인수 : {5} \n" +

    23                  "더블클릭 시간 : {6}ms \n 픽셀단위 영역 : {7}",

    24                  SystemInformation.MouseWheelPresent,

    25                  SystemInformation.MouseButtons,

    26                  SystemInformation.MouseButtonsSwapped,

    27                  SystemInformation.MouseSpeed,

    28                  SystemInformation.MouseWheelScrollDelta,

    29                  SystemInformation.MouseWheelScrollLines,

    30                  SystemInformation.DoubleClickTime,

    31                  SystemInformation.DoubleClickSize);

    32        txt_MouseInfo.Text = strMI;                              

    33     }

    34 }

별건 아니기 때문에 중요치는 않다.

무엇보다 중요한건 마우스 이벤트 처리가 어떻게 되는지 확인 하는 것이다. 아래의 코드는 콘솔에서 윈폼을 만들어 폼위에서 마우스 이벤트를 처리하는 코드이다. 꼭 코딩해보자.

  1. 4 using System.Windows.Forms;

    5

    6 namespace MouseEvent

    7 {

    8   class consoleMouseEvent : Form

    9   {

    10    public consoleMouseEvent()

    11    {

    12      this.Text = "마우스확인";

    13      this.MouseClick += new MouseEventHandler(cme_MouseClick);

    14      this.MouseDoubleClick += new MouseEventHandler(cme_MouseDoubleClick);

    15      this.MouseDown += new MouseEventHandler(cme_MouseDown);

    16      this.MouseUp += new MouseEventHandler(cme_MouseUp);

    17      this.MouseWheel += new MouseEventHandler(cme_MouseWheel);

    18      this.MouseMove += new MouseEventHandler(cme_MouseMove);

    19    }

    20

    21    static void Main(string[] args)

    22    {

    23      Application.Run(new consoleMouseEvent());

    24    }

    25

    26    protected void cme_MouseClick(object sender, MouseEventArgs me)

    27    {

    28      Console.WriteLine("{0} 마우스 클릭", me.Clicks);

    29    }

    30

    31    protected void cme_MouseDoubleClick(object sender, MouseEventArgs me)

    32    {

    33      Console.WriteLine("{0} 마우스 더블클릭", me.Button);

    34    }

    35

    36    protected void cme_MouseDown(object sender, MouseEventArgs me)

    37    {

    38      Console.WriteLine("{0} 마우스다운", me.Button);

    39    }

    40

    41    protected void cme_MouseUp(object sender, MouseEventArgs me)

    42    {

    43      Console.WriteLine("{0} 마우스업", me.Button);

    44    }

    45

    46    protected void cme_MouseWheel(object sender, MouseEventArgs me)

    47    {

    48      Console.WriteLine("{0} 마우스휠", me.Delta);

    49    }

    50

    51    protected void cme_MouseMove(object sender, MouseEventArgs me)

    52    {

    53      Console.WriteLine("{0}, {1} 마우스이동", me.X, me.Y);

    54    }      

    55  }

    56 }

 

 

[출처] : http://ssogarif.tistory.com/296

 

 

 

Comments