以wpf为例
接收进程代码
1.添加接收的触发事件
this.Title="窗体名字";
this.SourceInitialized += new EventHandler(win_SourceInitialized);
2.接收方法
void win_SourceInitialized(object sender, EventArgs e)
{
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
hwndSource.AddHook(new HwndSourceHook(WndProc));
}
}
private const int WM_COPYDATA = 0x004A; //当一个应用程序传递数据给另一个应用程序时发送此消息 固定代号 不能修改
protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_COPYDATA:
//你的代码
HandleCollector(hwnd, lParam);
handled = true;
break;
}
return IntPtr.Zero;
}
//WM_COPYDATA消息所要求的数据结构
public struct CopyDataStruct
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
private void HandleCollector(System.IntPtr hwnd, System.IntPtr lParam)
{
CopyDataStruct mmi = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
if (mmi.lpData == "最大化")
{
this.ShowInTaskbar = true;
Show();
Activate();
this.WindowState = WindowState.Maximized;
}
}
发送端
//WM_COPYDATA消息所要求的数据结构
public struct CopyDataStruct
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
public const int WM_COPYDATA = 0x004A; //当一个应用程序传递数据给另一个应用程序时发送此消息 固定代号 不能修改
//通过窗口的标题来查找窗口的句柄
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
//在DLL库中的发送消息函数
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage
(
int hWnd, // 目标窗口的句柄
int Msg, // 在这里是WM_COPYDATA
int wParam, // 第一个消息参数
ref CopyDataStruct lParam // 第二个消息参数
);
发送触发的方法
var msg = "最大化";
CopyDataStruct cds;
cds.dwData = (IntPtr)1; //这里可以传入一些自定义的数据,但只能是4字节整数
cds.lpData = msg; //消息字符串
cds.cbData = System.Text.Encoding.Default.GetBytes(msg).Length + 1; //注意,这里的长度是按字节来算的
SendMessage(FindWindow(null, "窗体名字"), WM_COPYDATA, 0, ref cds);