반응형

사실상 프로그램이 하는 일은 이벤트(event)에 대해 반응하는 것이 전부라고 말할 수 있다. 이벤트란 통상적으로 사용자의 키보드, 마우스, 스타일러스 펜의 입력을 의미한다. UIElement 클래스에는 키보드, 마우스, 스타일러스와 관련된 몇 가지의 이벤트가 정의돼 있으며, Window 클래스는 이 모든 이벤트를 상속받는다. 이런 이벤트 중 하나는 MouseDown 이다. 사용자가 윈도우의 클라이언트 영역을 누를 때마다 윈도우에서는 MouseDown 이벤트가 발생한다.

 

사용자가 윈도우 클라이언트 영역을 누를 때마다 MouseDown 이벤트가 발생된다. 이벤트 핸들러의 첫 번째 인자는 이벤트를 발생시키는 객체인데, 여기서는 Window 객체가 된다. 이벤트 핸들러는 이 객체를 Window 타입의 객체로 안전하게 형 변환한다.

 

이 프로그램에서 이벤트 핸들러에 Window 객체가 필요한 이유는 두 가지다. 첫 번째 이유는 MouseButtonEventArgs 클래스에 정의된 GetPosition 메소드의 인자로 Window 객체를 넘겨야 하기 때문이다. 이 GetPosition 메소드는 Point 타입(System.Windows에 정의된 구조체)의 객체를 반환하는데, 이 값은 인자로 넘긴 객체의 좌측 상단을 기준으로 한 마우스의 위치 좌표다. 두 번째 이유는 이벤트 핸들러가 Window 객체의 Title 프로퍼티를 읽어서 메시지 박스의 제목으로 사용하기 때문이다.

 

[HandleAnEvent.cs 파일]

using System;
using System.Windows;
using System.Windows.Input;

namespace HandleAnEvent
{
    public class HandleAnEvent
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();

            Window win = new Window();
            win.Title = "Handle An Event";
            win.MouseDown += WindowOnMouseDown;

            app.Run(win);
        }

        private static void WindowOnMouseDown(object sender, MouseButtonEventArgs args)
        {
            Window win = sender as Window;
            //Window win = Application.Current.MainWindow;
            string strMessage = string.Format("Window clicked with {0} button at point({1})", args.ChangedButton, args.GetPosition(win));

            MessageBox.Show(strMessage, win.Title);
            //MessageBox.Show(strMessage, Application.Current.MainWindow.Title);
        }
    }
}

 

프로젝트 다운로드

HandleAnEvent.zip
0.02MB

반응형

+ Recent posts