可以用2种方法来处理
1. 重载DefWndProc 方法
2. 继承IMessageFilter接口
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ReceiveMyMessage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(new MyMessageFilter());
}
public const int WM_USER = 0x0400;
public const int WM_TEST = WM_USER + 1;
[DllImport("user32", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hwnd, int msg, int wparam, int lparam);
private void button1_Click(object sender, EventArgs e)
{
SendMessage(Handle.ToInt32(), WM_TEST, 100, 200);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_TEST)
{
return;
}
base.WndProc(ref m);
}
}
public class MyMessageFilter : IMessageFilter
{
public const int WM_USER = 0x0400;
public const int WM_TEST = WM_USER + 1;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_TEST)
{
string message = string.Format("收到消息!参数为:{0},{1}", m.WParam, m.LParam);
MessageBox.Show(message); ///显示一个消息框
return true;
}
return false;
}
}
}