C# WinForm 两个窗体之间发送消息

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窗体再隐藏,用来后台做消息接受的程序。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值