日期:2008-05-11  浏览次数:20422 次

In C# we can filter our application's messages so some of them don't get dispatched. See the example below of how to prevent the user from clicking the Left Mouse button in our application:


// created on 20.10.2001 at 18:04
//This example has 2 classes
//1. MyFilter, which exposes the IMesageFilter interface
//The PreFilterMessage method is overriden for our needs
//2. MainForm, which is our main form
using System;
using System.Windows.Forms;
class MyFilter:IMessageFilter //gets the left mouse button messages
{
public bool PreFilterMessage(ref Message m)
{
  if (m.Msg>=513 && m.Msg<=515)
   {
    Console.WriteLine("mouse left button event NOT accepted!Filter working...");
    return(true);
   }
  return(false);
}
}
class MainForm : Form
{
private Button btn=new Button();
public MainForm() //MainForm's constructor
{
  //let's put a button on the form
  btn.Left=30;
  btn.Top=30;
  btn.Width=150;
  btn.Text="Try to Click me!";
  btn.Visible=true;
  this.Controls.Add(btn);
}
public static void Main()
{
  
  //let's put some filter on our Application's message queue
  Application.AddMessageFilter(new MyFilter());
  //create the MainForm object and make it visible
  Application.Run(new MainForm());
}
}