1、FormTest.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsTest
{
public partial class FormTest : Form
{
const int BM_CLICK = 0xF5;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
public FormTest()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
FormSub formSub = new FormSub();
formSub.Show();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
}
private void SendMessage(string pcMessage, string pcReceiveForm)
{
int WINDOW_HANDLER = FindWindow(null, pcReceiveForm);
if (WINDOW_HANDLER != 0)
{
SendMessage(WINDOW_HANDLER, BM_CLICK, 0, 0);
}
}
private void button2_Click(object sender, EventArgs e)
{
SendMessage("娃哈哈", "子窗体");
}
}
}
2、FormSub.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsTest
{
public partial class FormSub : Form
{
public FormSub()
{
InitializeComponent();
}
protected override void OnShown(EventArgs e)
{
this.Hide();
}
protected override void WndProc(ref Message m)
{
const int BM_CLICK = 0xF5;
if (m.Msg == BM_CLICK)
{
MessageBox.Show("子窗体收到事件");
}
else
{
base.WndProc(ref m);
}
}
}
}
修改FormSub窗体的标题为“子窗体”,这里在启动FormTest窗体的时候启动FormSub窗体再隐藏,用来后台做消息接受的程序。