이름 : MessageFilter.cs
using System;
using System.Windows.Forms;
class AppMain
{
public static void Main(string[] args)
{
Application.Run(new MyForm());
}
public class MyForm : System.Windows.Forms.Form
{
private Button btnOk;
public MyForm()
{
btnOk = new Button();
btnOk.Text = "&Ok";
btnOk.Click += new System.EventHandler(btnOk_Clicked);
btnOk.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(btnOk);
this.Text = "My Message Filter";
}
private void btnOk_Clicked(object sender, System.EventArgs e)
{
MessageBox.Show("clicked");
}
}
}
메시지 필터를 구현하려면 IMessageFilter를 구현하면 된다. IMessageFilter에서 구현해야하는 메소드는 다음과 같다.
bool PreFilterMessage(ref Message msg)
IMessageFilter를 구현하는 MyMessageFilter 클래스를 위 예제에 추가한다.
public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message msg)
{
// 왼쪽 마우스 버튼 이벤트를 가로챈다.
if ( 513 == msg.Msg ) // WM_LBUTTONDOWN = 513
{
MessageBox.Show("WM_LBUTTONDOWN is : " + msg.Msg.ToString());
return true;
}
return false;
} // end of method PreFilterMessage
} // end of class MyMessageFilter
WM_LBUTTONDOWN에서 WM은 윈도우 메시지(Window Message)를 뜻한다. LBUTTONDOWN이므로 마우스의 왼쪽 버튼을 누르는 순간을 가로채도록 지시한다.
private MyMessageFilter msgFilter = new MyMessageFilter();
public MyForm()
{
btnOk = new Button();
btnOk.Text = "&Ok";
btnOk.Click += new System.EventHandler(btnOk_Clicked);
btnOk.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(btnOk);
Application.AddMessageFilter(msgFilter);
this.Text = "My Message Filter";
}
실행하고 버튼을 클릭하면 "clicked" 대신에 다른 메시지가 나타나는 것을 볼 수 있을 것이다. 마우스와 관련하여 자주 사용되는 윈도우 메시지는 다음과 같다.
|
윈도우 메시지
|
16진수
|
10진수
|
내용
|
| WM_MOUSEMOVE | 0x0200 | 512 | 마우스 이동 |
| WM_LBUTTONDOWN | 0x0201 | 513 | 마우스 왼쪽 버튼을 누르고 있는 상태 |
| WM_LBUTTONUP | 0x0202 | 514 | 마우스 왼쪽 버튼을 떼었을 때 |
| WM_LBUTTONDBLCLK | 0x0203 | 515 | 마우스 왼쪽 버튼을 더블 클릭할 때 |
| WM_RBUTTONDOWN | 0x0204 | 516 | 마우스 오른쪽 버튼을 누르고 있는 상태 |
| WM_RBUTTONUP | 0x0205 | 517 | 마우스 오른쪽 버튼을 떼었을 때 |
| WM_RBUTTONDBLCLK | 0x0206 | 518 | 마우스 오른쪽 버튼을 더블 클릭할 때 |
| WM_MOUSEWHEEL | 0x020A | 522 | 마우스 휠을 움직일 때 |
최신 콘텐츠