本文主要是介绍C# 软件间通讯方式之WM_COPYDATA,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为了实现不同软件间通讯实现代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testmessage
{
public partial class Form1 : Form
{
const int WM_COPYDATA = 0x004A;
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
[DllImport("User32.dll")]
public static extern int SendMessage(int hwnd, int msg, int wParam, ref COPYDATASTRUCT lParam);
[DllImport("User32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);
public Form1()
{
InitializeComponent();
}
public bool sendmessageto(string windowname, string data)
{
int WINDOW_HANDLE = FindWindow(null, windowname);
if (WINDOW_HANDLE != 0)
{
byte[] arr = System.Text.Encoding.Default.GetBytes(data);
int len = arr.Length;
COPYDATASTRUCT cdata;
cdata.dwData = (IntPtr)100;
cdata.lpData = data;
cdata.cData = len + 1;
SendMessage(WINDOW_HANDLE, WM_COPYDATA, 0, ref cdata);
return true;
}
else
return false;
}
protected override void DefWndProc(ref Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT cdata = new COPYDATASTRUCT();
Type mytype = cdata.GetType();
cdata = (COPYDATASTRUCT)m.GetLParam(mytype);
this.label1.Text = cdata.lpData;
break;
default:
base.DefWndProc(ref m);
break;
}
}
private void send_Click(object sender, EventArgs e)
{
sendmessageto(this.Windowname.Text, this.Message.Text);
}
}
}
测试软件和源代码下载位置: http://download.csdn.net/detail/snowbird13/9899896
里面两个exe,可以填上相互窗口名字,输入信息可以互相发送。
这篇关于C# 软件间通讯方式之WM_COPYDATA的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!