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 消息的更多相关文章

  1. c++与C# winform的消息通讯--(结构体与byte数组的使用)

    近期正在做一个蓝牙驱动的使用程序,其中有一块从c++发送数据到C#的部分,网上查了很多资料,大多都是介绍如何通过调用函数获取用户数据.并且在消息发送中,很少介绍如何发送一个结构体,并且结构体里面有 b ...

  2. C# 进程间通信之二传递复杂数据类型(转)

    从C#下使用WM_COPYDATA传输数据说到Marshal的应用 笔者曾在一个项目的实施过程中,需要使用WM_COPYDATA在本地机器的两个进程间传输数据.在C++中实现非常简单,但在C#中实现时 ...

  3. Shuttle ESB(六)——在工程中的应用

    假设你可能浏览在前面几篇文章ESB介绍,我相信,在这篇文章中,你会发现很多共鸣. 虽然.市面上开源的ESB确实很之多.像Java中的Mule ESB.Jboss ESB:.Net中的NServiceB ...

  4. WPF + Winform 解决管理员权限下无法拖放文件的问题

    wpf,winform混合解决管理员权限无法拖放文件的问题 学习自: https://zhuanlan.zhihu.com/p/343369663 https://zhuanlan.zhihu.com ...

  5. windows进程通信 -- WM_COPYDATA消息

    WM_COPYDATA消息,在win32中用来进行进程间的数据传输. typedef struct tagCOPYDATASTRUCT { // cds DWORD dwData; DWORD cbD ...

  6. 【Qt】Qt之进程间通信(Windows消息)【转】

    简述 通过上一节的了解,我们可以看出进程通信的方式很多,今天分享下如何利用Windows消息机制来进行不同进程间的通信. 简述 效果 发送消息 自定义类型与接收窗体 发送数据 接收消息 设置标题 重写 ...

  7. Qt之进程间通信(Windows消息)

    简述 通过上一节的了解,我们可以看出进程通信的方式很多,今天分享下如何利用Windows消息机制来进行不同进程间的通信. 简述 效果 发送消息 自定义类型与接收窗体 发送数据 接收消息 设置标题 重写 ...

  8. 使用copydata实现进程之间数据传递

    Winform to Winfrom==> 发送端==> using System; using System.Runtime.InteropServices; namespace Cop ...

  9. C# 通过copydata实现进程间通信

    最近公司需要实现一个基于copydata进程间通信的功能.原来一直没有接触过Windows的进程通信,这次正好可以学习一下. 程序是基于Winform的,下面直接上代码. 公共类: public cl ...

随机推荐

  1. Java--对象与类(二)

    final 实例域 可以将实例域定义为final.构建对象时必须初始化这样的域.也就是说在一个构造器执行之后,这个域被设置,并且之后无法对其修改 final 修饰符大多应用于基本(primitive) ...

  2. python爬虫(九) requests库之post请求

    1.方法: response=requests.post("https://www.baidu.com/s",data=data) 2.拉勾网职位信息获取 因为拉勾网设置了反爬虫机 ...

  3. ToString 奇淫技巧

    int和float同样结果 decimal decTemp = 2.1m; Console.WriteLine(decTemp.ToString("#0.00")); //输出2. ...

  4. a链接 打电话 发短信 发email

    <a href="tel:10086">给10086打电话</a><a href="sms:10086">给10086发短信 ...

  5. 图解JVM--(二)垃圾回收

    垃圾回收 1.如何判断对象可以回收 1.1 引用计数 在对象中添加一个引用计数器,每当有一个地方引用它,计数器值就加一,当引用失效时,计数器值就减一,任何时刻计数器为零的对象就不可能再被使用的,就可以 ...

  6. 为kubernetes-dashboard页面增加过期时间,减少登录次数.

    方法很多,最简单的就是登录后,找到Deployments 服务, 右侧界面会出现kubernetes-dashboard的项目,如果没出现,那么在namespace那里选择全部名称空间. ports: ...

  7. 若块级元素被设置为 display: table-cell 便无法设置宽度

    工作中,遇到表格的单元格中的 div 设置宽度无效,后来是发现 div 被设置为 display: table-cell ,后将其修改为 display: block 则设置的宽度生效.

  8. 136、Java的内部类

    01.代码如下: package TIANPAN; class Outer { // 外部类 private String msg = "Hello World !"; class ...

  9. zabbix监控 -mysql数据库

    1.禁用安装防护[root@mysql213 ~]# vi /etc/selinux/config #关闭安装 SELINUX=disabled 2.授权zabbix监控账号 mysql -uroot ...

  10. 【剑指Offer面试编程题】题目1366:栈的压入、弹出序列--九度OJ

    题目描述: 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈 ...