WinForm中使用Win32API发送自定义消息

本文介绍了一个使用Windows消息机制实现的跨进程通信案例。通过注册窗口消息并在不同应用程序间发送消息来触发特定事件,实现了AppA与AppB之间的简单交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I let AppA's Button1 to invoke the Button1_click event in AppB
In AppB I wrote:
private string msgstr = "interprocess communication";
private uint msg;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
private void Form1_Load(object sender, System.EventArgs e)
{
msg = RegisterWindowMessage(msgstr);
if (msg == 0)
{
MessageBox.Show(Marshal.GetLastWin32Error().ToString());
}
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("AppB's button is clicked");
}
protected override void WndProc(ref Message m)
{
if (m.Msg == msg)
{
//MessageBox.Show(msgstr + " from wndproc");
button1.PerformClick();
}
base.WndProc(ref m);
}
And in AppA I wrote:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam,
IntPtr lparam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);

private string msgstr = "interprocess communication";
private uint msg;
private const int HWND_BROADCAST = 0xffff;
private void button1_Click(object sender, System.EventArgs e)
{
msg = RegisterWindowMessage(msgstr);
if (msg == 0)
{
MessageBox.Show(Marshal.GetLastWin32Error().ToString());
}
PostMessage(HWND_BROADCAST, msg, IntPtr.Zero, IntPtr.Zero);
}
PS. Both should using System.Runtime.InteropServices;if PostMessage doesn't work you can try SendMessage
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值