c# copydata 消息
using PublicCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace broadcast2
{
public partial class broadcast2 : Form
{
IPAddress IP = null;
EndPoint SendEP = null;
Socket sock = null; private string logfile = "";
private int index = ;
private Thread rcvThread = null;
public broadcast2()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen; sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.EnableBroadcast = true; textBox2.Text = this.Handle.ToString();
logfile = Path.Combine(Application.StartupPath, "logs.txt"); this.Text = "发送者";
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m); if (m.Msg == 0x04A)
{
COPYDATASTRUCT cdata = new COPYDATASTRUCT();
Type mytype = cdata.GetType();
cdata = (COPYDATASTRUCT)m.GetLParam(mytype);
MessageBox.Show(cdata.lpData);
} if (m.Msg == 1025)
{
string text = "";
PublicUtils.GlobalGetAtomName(m.LParam.ToInt32(), text, 1024); MessageBox.Show(text);
}
} private void button2_Click(object sender, EventArgs e)
{
//PublicUtils.SendFormMsg_Copydata(PublicUtils.FindWindow("TForm2", "Form2"), "xxx 暗室逢灯12345 54321"); PublicUtils.SendFormMsg(PublicUtils.FindWindow("TForm2", "Form2"), "xxx 暗室逢灯12345 54321--");
} private void Send()
{
//byte[] sendbuf = Encoding.UTF8.GetBytes(string.Format("消息 {0}", ++index));
byte[] sendbuf = Encoding.UTF8.GetBytes(DateTime.Now.ToString("HHmmss"));
sock.SendTo(sendbuf, SendEP);
//Console.WriteLine(string.Format("{0} 发送广播消息 {1}", DateTime.Now.ToString("HH:mm:ss.fff"), i));
writeLog(string.Format("{0} 发送广播消息 {1}", DateTime.Now.ToString("HH:mm:ss.fff"), DateTime.Now.ToString("HHmmss"))); //byte[] receiveBuf = new byte[1000];
//sock.Receive(receiveBuf);
//string msg = Encoding.UTF8.GetString(receiveBuf, 0, receiveBuf.Length);
////Console.WriteLine(string.Format("{0} 收到回复: {0}", DateTime.Now.ToString("HH:mm:ss.fff"), msg);
//writeLog(string.Format("{0} 收到回复: {1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg)); } private void writeLog(string text)
{
using (StreamWriter sw = new StreamWriter(logfile, true, Encoding.UTF8))
{
sw.WriteLine(text);
}
} private void button1_Click(object sender, EventArgs e)
{
index = ;
if (!timer1.Enabled)
{
IP = IPAddress.Parse(textBox1.Text.Trim());
SendEP = new IPEndPoint(IP, ); timer1.Start();
button1.Text = "停止";
textBox1.Enabled = false; rcvThread = new Thread(new ThreadStart(DoReceive));
rcvThread.IsBackground = true;
rcvThread.Start();
}
else
{
timer1.Stop();
button1.Text = "开始";
textBox1.Enabled = true; if (rcvThread != null)
{
rcvThread.Abort();
rcvThread = null;
}
}
} /// <summary>
/// 方式一:阻塞接收的方式
/// </summary>
private void DoReceive()
{
while (true)
{
try
{
byte[] receiveBuf = new byte[];
sock.Receive(receiveBuf);
string msg = Encoding.UTF8.GetString(receiveBuf, , receiveBuf.Length);
//Console.WriteLine(string.Format("{0} 收到回复: {0}", DateTime.Now.ToString("HH:mm:ss.fff"), msg);
string stext = string.Format("{0} 收到:{1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg).Replace('\0', ' ').Trim();
writeLog(stext);
}
catch
{ }
}
}
/// <summary>
/// 方式二:监听方式,这种方式不行
/// </summary>
private void DoReceive2()
{
UdpClient listener = new UdpClient();
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, );
listener.ExclusiveAddressUse = false;
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Client.Bind(endPoint);
while (true)
{
byte[] receiveBuf = listener.Receive(ref endPoint);
string msg = Encoding.UTF8.GetString(receiveBuf, , receiveBuf.Length);
string stext = string.Format("{0}收到:{1}", DateTime.Now.ToString("HH:mm:ss.fff"), msg).Replace('\0', ' ').Trim();
writeLog(stext);
}
} private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
timer1.Stop();
Application.Exit();
} private void timer1_Tick(object sender, EventArgs e)
{
Send();
}
public static void UdpServer(IPEndPoint serverIP)
{
bool thread_flag = true;
Console.WriteLine("UDP服务器开始监听" + serverIP.Port + "端口");
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(serverIP);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, );
EndPoint Remote = (EndPoint)ipep;
new Thread(() =>
{
while (thread_flag)
{
byte[] data = new byte[];
int length = ;
try
{
length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string message = Encoding.UTF8.GetString(data, , length);
string ipport = (Remote as IPEndPoint).Address.ToString() + ":" + (Remote as IPEndPoint).Port.ToString();
Console.WriteLine(string.Format("{0} 收到來自{1}的消息:{2}", datetime, ipport, message));
}
udpServer.Close();
}).Start();
}
}
}
公用单元文件:
PublicUtils.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace PublicCode
{
public static class PublicUtils
{
public const int WM_TextNotify = ; [DllImport("User32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hwnd, int msg, int wParam, ref COPYDATASTRUCT IParam);
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage2(int hwnd, int wMsg, int wParam, int lParam);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] public static extern int GlobalAddAtom(string lpString); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern int GlobalDeleteAtom(int atom); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern uint GlobalGetAtomName(int nAtom, string lpBuffer, int nSize); public static void SendFormMsg_Copydata(IntPtr handle, string atext)
{
byte[] arr = Encoding.Unicode.GetBytes(atext);
int len = arr.Length;
COPYDATASTRUCT cdata;
cdata.dwData = (IntPtr);
cdata.lpData = atext;
cdata.cData = len + ;
SendMessage(handle, 0x04A, , ref cdata);
} public static void SendFormMsg(IntPtr handle, string atext)
{
int atom = GlobalAddAtom(atext);
SendMessage2((int)handle, WM_TextNotify, , atom);
GlobalDeleteAtom(atom);
}
} public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cData;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpData;
}
}
更正:
IntPtr stext = Marshal.AllocHGlobal(1024);
if (m.Msg == )
{
PublicUtils.GlobalGetAtomName(m.LParam.ToInt32(), stext, );
textBox3.Text = Marshal.PtrToStringUni(stext);
Marshal.FreeHGlobal(stext);
}
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern uint GlobalGetAtomName(int nAtom, IntPtr lpBuffer, int nSize);
c# copydata 消息的更多相关文章
- c++与C# winform的消息通讯--(结构体与byte数组的使用)
近期正在做一个蓝牙驱动的使用程序,其中有一块从c++发送数据到C#的部分,网上查了很多资料,大多都是介绍如何通过调用函数获取用户数据.并且在消息发送中,很少介绍如何发送一个结构体,并且结构体里面有 b ...
- C# 进程间通信之二传递复杂数据类型(转)
从C#下使用WM_COPYDATA传输数据说到Marshal的应用 笔者曾在一个项目的实施过程中,需要使用WM_COPYDATA在本地机器的两个进程间传输数据.在C++中实现非常简单,但在C#中实现时 ...
- Shuttle ESB(六)——在工程中的应用
假设你可能浏览在前面几篇文章ESB介绍,我相信,在这篇文章中,你会发现很多共鸣. 虽然.市面上开源的ESB确实很之多.像Java中的Mule ESB.Jboss ESB:.Net中的NServiceB ...
- WPF + Winform 解决管理员权限下无法拖放文件的问题
wpf,winform混合解决管理员权限无法拖放文件的问题 学习自: https://zhuanlan.zhihu.com/p/343369663 https://zhuanlan.zhihu.com ...
- windows进程通信 -- WM_COPYDATA消息
WM_COPYDATA消息,在win32中用来进行进程间的数据传输. typedef struct tagCOPYDATASTRUCT { // cds DWORD dwData; DWORD cbD ...
- 【Qt】Qt之进程间通信(Windows消息)【转】
简述 通过上一节的了解,我们可以看出进程通信的方式很多,今天分享下如何利用Windows消息机制来进行不同进程间的通信. 简述 效果 发送消息 自定义类型与接收窗体 发送数据 接收消息 设置标题 重写 ...
- Qt之进程间通信(Windows消息)
简述 通过上一节的了解,我们可以看出进程通信的方式很多,今天分享下如何利用Windows消息机制来进行不同进程间的通信. 简述 效果 发送消息 自定义类型与接收窗体 发送数据 接收消息 设置标题 重写 ...
- 使用copydata实现进程之间数据传递
Winform to Winfrom==> 发送端==> using System; using System.Runtime.InteropServices; namespace Cop ...
- C# 通过copydata实现进程间通信
最近公司需要实现一个基于copydata进程间通信的功能.原来一直没有接触过Windows的进程通信,这次正好可以学习一下. 程序是基于Winform的,下面直接上代码. 公共类: public cl ...
随机推荐
- mysql 连接数据库时时区报错
1.url: jdbc:mysql://192.168.0.101:3306/testdb?serverTimezone=UTC,在连接字符后面添加时区设置 2.使用navicat或者直接使用mysq ...
- Css——显示2行数据,超出显示...
解决需求——数据较长时,只显示两行,超出显示... .showTwoRow { text-align: left; text-overflow: ellipsis; display: -webkit- ...
- idea 编译maven
参考:https://blog.csdn.net/yye894817571/article/details/71681891
- SpringCloud入门——(1)创建Eureka项目
Eureka是Spring Cloud Netflix微服务套件中的一部分,可以与Springboot构建的微服务很容易的整合起来.Eureka包含了服务器端和客户端组件.服务器端,也被称作是服务注册 ...
- day22-Python运维开发基础(正则函数 / 异常处理)
1. 正则函数 # ### 正则表达式 => 正则函数 import re # search 通过正则匹配出第一个对象返回,通过group取出对象中的值 strvar = "5*7 9 ...
- 设计模式课程 设计模式精讲 11-2 装饰者模式coding
1 代码演练 1.1 代码演练1(未使用装饰者模式) 1.2 代码演练2(使用装饰者模式) 1 代码演练 1.1 代码演练1(未使用装饰者模式) 需求: 大妈下班卖煎饼,加一个鸡蛋加一元,一个火腿两元 ...
- UniGUI之Login窗口(10)
在UniGUI的CHM帮助里读到的. 一定要新建一个其他空白的工程,然后再添加LoginForm LoginForm 是另一种特殊的表单类型, 仅用于登录目的. 此操作将创建一个与常规窗体外观相同的空 ...
- 笔记||Pyhthon3进阶之多线程操作共享数据
# 多线程操作共享数据--------------------------------------------------------------- # import threading# 使用锁# ...
- 一 注册功能&登录功能,权限拦截
注册功能: 前端JSP:提供表单注册信息以及访问路径,发送请求到Strus2. Struts2 : 通过模型驱动接收并封装User对象,Spring依赖注入(无参构造+setter方法)获取业务层Us ...
- ionic3记录之APP运行时网络判断
判断设备网路是否正常: 安装插件: ionic cordova plugin add cordova-plugin-network-information npm install --save@nat ...