监听Windows消息

在WinForm开发中,有时需要监听应用程序的全局消息,可以继承IMessageFilter接口。执行Application.AddMessageFilter(this)开始接收消息,在销毁之前执行Application.RemoveMessageFilter(this)

public MyListener : Lable, IMessageFilter

{

        #region IMessageFilter 成员

        const int WM_KEYDOWN = 0x100;
        const int WM_SYSKEYDOWN = 0x104;
        const int WM_KEYUP = 0x101;
        const int WM_SYSKEYUP = 0x105;

        public bool PreFilterMessage(ref Message m)
        {
            ////System.Diagnostics.Debug.WriteLine(m);

            bool handle = false;
            if (m.WParam.ToInt32() == (int)Keys.Escape && m.Msg == WM_KEYUP)
            {

        //执行Escape
              }
            else if (IsPressCursorKey(ref m))
            {
                //如果有选择,则处理。
                     MoveControl((Keys)m.WParam.ToInt32());
                    handle = true;      //过滤消息
             }
            else if (m.WParam.ToInt32() == (int)Keys.Delete && m.Msg == WM_KEYUP)
            {
                //删除选择的控件。
            }
            return handle;
        }

        private static bool IsPressCursorKey(ref Message m)
        {
            return (m.Msg == WM_KEYDOWN || m.Msg == WM_SYSKEYDOWN) && (m.WParam.ToInt32() == (int)Keys.Up
                            || m.WParam.ToInt32() == (int)Keys.Down || m.WParam.ToInt32() == (int)Keys.Left || m.WParam.ToInt32() == (int)Keys.Right);
        }

        #endregion

}

原文地址:https://www.cnblogs.com/Yjianyong/p/1664212.html