C#⾃定义结构体的(⽤SendMessage)传递要传递结构体
public struct STUDENT
{
public int id; //ID
public string name; //姓名
}
要引⽤Win32api函数FindWindow,SendMessage
///<summary>
///查窗体句柄
///</summary>
///<param name="lpClassName">指定的类名</param>
/
//<param name="lpWindowName">指定的窗⼝名称</param>
///<returns>返回窗⼝句柄</returns>
[DllImport("User32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(
string lpClassName,
string lpWindowName);
///<summary>
///查窗体句柄
///</summary>
///<param name="hwndParent">⽗窗⼝句柄</param>
///<param name="hwndChildAfter">⼦窗⼝句柄</param>
/
//<param name="lpClassName">窗⼝类名</param>
///<param name="lpWindowName">窗⼝名称</param>
///<returns></returns>
[DllImport("User32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(
IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpClassName,
string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(
IntPtr hWnd, // 窗⼝句柄
int Msg, // message
int wParam, // first message parameter
IntPtr lParam); // second message parameter
3,还要定义个消息
public const int WM_COPYDATA = 0X004A;
也可以发送⾃定义消息 public const int WM_USER = 1024; //⾃定义消息
4,发送消息
//先查要发送的窗⼝句柄
IntPtr nRet = Win32API.FindWindowEx(IntPtr.Zero, IntPtr.Zero,null , "Form2");
if (nRet == IntPtr.Zero)
MessageBox.Show("没有到指定的窗⼝");
STUDENT stu = new STUDENT();
stu.id = 101;
stu.name = "我是发送者";
IntPtr stuPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STUDENT)));
Marshal.StructureToPtr(stu, stuPtr, false);
SendMessage(nRet, WM_COPYDATA, 0, stuPtr);
//⽤PostMessage发送消息
//PostMessage(nRet, WM_USER, 0, stuPtr);
5,在接收窗⼝中重写DefWndProc函数
public const int WM_COPYDATA = 0X004A;
public const int WM_USER = 1024; //⾃定义消息
protected override void DefWndProc(ref Message m)
{
if(m.Msg==WM_COPYDATA)
{
STUDENT stu = (STUDENT)Marshal.PtrToStructure(m.LParam, typeof(STUDENT));
textBox1.Text = stu.name;
return;
}
if(m.Msg==WM_USER)
{
STUDENT stu = (STUDENT)Marshal.PtrToStructure(m.LParam, typeof(STUDENT));
textBox1.Text = stu.name;
return;
}
base.DefWndProc(ref m);
}
6,在接收窗⼝也要定义WM_COPYDATA消息,和结构体,
7,在WM_COPYDATA传递COPYDATASTRUCT结构体也是可⾏的
IntPtr cdsPtr = IntPtr.Zero;
cdsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
param nameMarshal.StructureToPtr(cds, cdsPtr, false);
SendMessage(nRet, WM_COPYDATA, 0, cdsPtr);
接收窗⼝中
COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); textBox1.Text = cds.lpData;
注意:要⽤Marshal类要加命名空间 using System.Runtime.InteropServices;
今天就弄到这了,其他的API以后有时间再弄
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论