c#使用句柄进行通信

这部分分为3部分。

一、2个exe程序之间通信,第一个程序发送消息,第二个程序实时接收消息。

二、2个exe程序之间通信,第一个程序发送命令执行第二窗口中的按钮事件。

三、2个exe程序之间通信,第一个程序发送消息到第二个程序中的某一个控件中。

一,2个exe程序之间通信,第一个程序发送消息,第二个程序实时接收消息。

1.建立第一个程序,界面如下

2.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Demo
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
       int hWnd,
       int Msg,
       int wParam,
       ref COPYDATASTRUCT lParam
       );
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string
        lpWindowName);



        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            int WINDOW_HANDLER = FindWindow(null, "Form1");//获取Form1的句柄,一定是第二个程序的名字

            byte[] sarr = System.Text.Encoding.Default.GetBytes(textBox1.Text);
            int len = sarr.Length;

            COPYDATASTRUCT cds;
            cds.dwData = (IntPtr)100;
            cds.lpData = textBox1.Text;
            cds.cbData = len + 1;
            SendMessage(WINDOW_HANDLER, 0x004A, 0, ref cds);

        }
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
    }
}

 3.建立第二个程序

 4.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case 0x004A://处理消息                    
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    this.richTextBox1.Text = mystr.lpData;
                    break;
                default:
                    base.DefWndProc(ref m);//调用基类函数处理非自定义消息。 
                    break;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

    }
}

注意:Form1一定是第二个程序的名字

5.,运行2个exe,点击发送按钮,效果


二、2个exe程序之间通信,第一个程序发送命令执行第二窗口中的按钮事件。

1.建立一个程序,第一个界面

2.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Demo
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            IntPtr hwnd_win;
            IntPtr hwnd_button;

            hwnd_win = FindWindow(null, "Form1");//得到Form1的句柄 
            hwnd_button = FindWindowEx(hwnd_win, new IntPtr(0), null, "按钮");//得到Form1中按钮的句柄
            const int BM_CLICK = 0x00F5;
            Message msg = Message.Create(hwnd_button, BM_CLICK, new IntPtr(0), new IntPtr(0));
            PostMessage(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);

        }

    }
}

 3.第二个界面

4.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("你好");
        }
    }
}

 5.,运行2分exe,点击发送按钮,效果

三、2个exe程序之间通信,第一个程序发送消息到第二个程序中的某一个控件中。

1.第一个程序界面

2.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Demo
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            const int WM_CHAR = 0x0102;
            IntPtr hwnd_win;
            IntPtr hwnd_textbox;

            hwnd_win = FindWindow(null, "Form1");
            hwnd_textbox = FindWindowEx(hwnd_win, new IntPtr(0), null, "消息");

            UnicodeEncoding encode = new UnicodeEncoding();
            char[] chars = encode.GetChars(encode.GetBytes(textBox1.Text));
            Message msg;
            foreach (char c in chars)
            {
                msg = Message.Create(hwnd_textbox, WM_CHAR, new IntPtr(c), new IntPtr(0));
                PostMessage(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);
            }
        }

    }
}

 3.第二个程序只需要拖一个接收消息的textBox1,里面写上消息二字,因为第一个程序要获取它

 4.运行2个exe,点击发送按钮,效果

这里获取的都是句柄,调用的方法都是Windows api函数。需要了解Windows API的可以看关于《精通Windows.API-函数、接口、编程实例》 这本书 

来源:c#使用句柄进行通信_c# 句柄-CSDN博客

  • 0
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
C#中,句柄(Handle)是一个引用或指针,用于表示对托管对象或非托管资源的引用。句柄可以被用于与底层系统交互、管理资源、进行跨 AppDomain 或进程通信等操作。 在C#中,使用句柄可以通过以下方式进行: 1. 托管句柄(Managed Handle):这是对.NET对象的引用,由CLR(Common Language Runtime)进行管理和释放。在C#中,托管句柄的创建和使用是自动的,开发者无需手动管理托管句柄的生命周期。 2. 非托管句柄(Unmanaged Handle):这是对非托管资源(如操作系统提供的资源)的引用。在C#中,可以使用`IntPtr`类型表示非托管句柄。通过调用外部API函数或使用`Marshal`类中的方法,可以获取或创建非托管句柄,并进行相关操作。 以下是使用非托管句柄的一个简单示例: ```csharp using System; using System.Runtime.InteropServices; class Program { // 假设有一个外部API函数,返回一个非托管句柄 [DllImport("mylibrary.dll")] private static extern IntPtr GetHandle(); static void Main() { IntPtr handle = GetHandle(); // 调用一些需要使用句柄的操作 DoSomethingWithHandle(handle); // 释放非托管句柄 ReleaseHandle(handle); } static void DoSomethingWithHandle(IntPtr handle) { // 使用句柄进行一些操作 // ... } static void ReleaseHandle(IntPtr handle) { // 释放句柄的资源 // ... } } ``` 请注意,在使用非托管句柄时,需要确保正确地管理它们的生命周期,包括获取、使用和释放资源。这样可以避免资源泄漏和潜在的安全问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故里2130

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值