日期:2010-07-30  浏览次数:20490 次

  比较常用的是重载Form的DefWndProc方法,例如截取鼠标按下的消息:

protected override void DefWndProc(ref Message m)
        {
            if ( m.Msg ==  0x0201 )
            {
                MessageBox.Show(m.Msg.ToString());
            }
            else
            {
                base.DefWndProc (ref m);
            }
        }

  还可以通过另一种办法,使用IMessageFilter 接口:

public class MessageFilter : IMessageFilter
    {
                public bool PreFilterMessage(ref Message m)
               {
                        if (m.Msg == 0x0201)
                       {
                                MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
                               return true;
                       }
                       return false;
        }

    }

  然后使用Application.AddMessageFilter方法,例如:

private static MessageFilter msgFliter = new MessageFilter();

  在Main方法中注册消息筛选器:

Application.AddMessageFilter(msgFliter);

  如果要取消注册,可以调用Application.RemoveMessageFilter方法