Winform to Winfrom==>
发送端==》
using System;
using System.Runtime.InteropServices;
namespace CopyData.Sender
{
public partial class Form1 : System.Windows.Forms.Form
{
const int WM_COPYDATA = 0x004A;
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
public Form1()
{
InitializeComponent();
}
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
ref COPYDATASTRUCT lParam // second message parameter
);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string
lpWindowName);
private void button1_Click(object sender, System.EventArgs e)
{
int WINDOW_HANDLER = FindWindow(null, @"Form1");
if (WINDOW_HANDLER == 0)
{
}
else
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(this.textBox1.Text);
int len = sarr.Length;
COPYDATASTRUCT cds;
cds.dwData = (IntPtr)100;
cds.lpData = this.textBox1.Text;
cds.cbData = len + 1;
SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
}
}
}
}
接收端==》
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace CopyData.Receiver { public partial class Form1 : Form { public Form1() { InitializeComponent(); } const int WM_COPYDATA = 0x004A; //[StructLayout(LayoutKind.Sequential)] public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { //接收自定义消息 USER,并显示其参数 case WM_COPYDATA: COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); mystr = (COPYDATASTRUCT)m.GetLParam(mytype); this.textBox1.Text = mystr.lpData; break; default: base.DefWndProc(ref m); break; } } } }
运行效果如下:
注意:
int
WINDOW_HANDLER = FindWindow(
null
,
@"Form1"
); —— 用于确定发送方发送数据到其他进程的某个标题为Form1的窗体。
2.delhpi程序与C#程序进行消息发送时,出现如下问题,解决思路?
a.安装.netframework
b.检查delphi以及C#程序(例如,delphi==>cdds.cbData := length(Edit1.Text)+1;cdds.lpData := pchar(Edit1.Text);)是否正确?
WPF to Winfrom to WPF==>
发送方: WPF to WinFrom
private void QueueCode(int queueType) { IntPtr hwnd = ((HwndSource)PresentationSource.FromVisual(this)).Handle; int sendHandle = hwnd.ToInt32(); int WINDOW_HANDLER = FindWindow(null, @"Form1"); if (WINDOW_HANDLER == 0) { StartQueueExe(); WINDOW_HANDLER = FindWindow(null, @"Form1"); } string queueName = this.cbQueue.Text; queueName = queueType + "^" + this.cbQueue.Text + "^" + sendHandle; if (WINDOW_HANDLER == 0) { } else { byte[] sarr = System.Text.Encoding.Default.GetBytes(queueName); int len = sarr.Length; COPYDATASTRUCT cds; cds.dwData = (IntPtr)100; cds.lpData = queueName; cds.cbData = len + 1; SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds); } var hwndSource = (HwndSource)HwndSource.FromVisual(this); hwndSource.AddHook(new HwndSourceHook(WndProc)); } private void StartQueueExe() { string filePath = AppDomain.CurrentDomain.BaseDirectory + "TEST.exe"; System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = filePath; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 p.StartInfo.CreateNoWindow = true;//不显示程序窗口 p.Start();//启动程序 Thread.Sleep(500); } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case WM_COPYDATA: COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal .PtrToStructure(lParam, typeof(COPYDATASTRUCT)); this.lblQueueMessage.Content = cds.lpData; break; default: break; } return (System.IntPtr)0; }
接收方:WinFrom获取
#region 获取消息 /// <summary> /// 0x004A /// </summary> const int WM_COPYDATA = 0x004A; //[StructLayout(LayoutKind.Sequential)] public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } protected override void DefWndProc(ref System.Windows.Forms.Message m) { try { switch (m.Msg) { // 接收自定义消息 USER,并显示其参数 case WM_COPYDATA: COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); mystr = (COPYDATASTRUCT)m.GetLParam(mytype); ReceiveMessage = mystr.lpData; break; default: base.DefWndProc(ref m); break; } } catch { return; } } #endregion
Winfrom to WPF
private static string FormTitle = "Form1"; [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage( int hWnd, // handle to destination window int Msg, // message int wParam, // first message parameter ref COPYDATASTRUCT lParam // second message parameter ); [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern int FindWindow(string lpClassName, string lpWindowName); public bool SendMessage(int value, int queueType) { try { StringBuilder content = new StringBuilder(); if (value != 0)//没有全部被预约 { // string appointTimes = DateTime.Now.ToLongTimeString().ToString(); if (string.IsNullOrEmpty(CurrentDate)) CurrentDate = DateTime.Now.ToShortDateString(); int num = DBQSQueueBusiness.GetCountByCondition(QueueId, CurrentDate); CurrentDate = DateTime.Parse(CurrentDate).ToString("yyyy-MM-dd"); content.Append(CurrentDate);//日期 content.Append("^"); content.Append(CurrentTimePart);//描述appointTimes content.Append("^"); content.Append(value);//号 content.Append("^"); content.Append(QueueId);//队列 content.Append("^"); if (queue == null) queue = new V_Queue(); queue.ENROLDATE = CurrentDate; queue.APPOINTTIME = CurrentTimePart;//appointTimes queue.SORTNO = value; } else content.Append("0"); //int WINDOW_HANDLER = FindWindow(null, @FormTitle); int WINDOW_HANDLER = int.Parse(FormTitle); if (WINDOW_HANDLER == 0) { } else { byte[] sarr = System.Text.Encoding.Default.GetBytes(content.ToString()); int len = sarr.Length; COPYDATASTRUCT cds; cds.dwData = (IntPtr)100; cds.lpData = content.ToString(); cds.cbData = len + 1; SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds); } } catch { return false; } return true; }
WPF 接收方:
#region 定义常量消息值 public const int WM_GETTEXT = 0x0D; public const int WM_SETTEXT = 0x0C; public const int WM_SIZEING = 0x0214; public const int WM_COPYDATA = 0x004A; public const int WM_LBUTTONDBLCLK = 0x0203; #endregion #region 定义结构体 public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } #endregion private void Window_Loaded(object sender, RoutedEventArgs e) { HwndSource hWndSource; WindowInteropHelper wih = new WindowInteropHelper(this); hWndSource = HwndSource.FromHwnd(wih.Handle); //添加处理程序 hWndSource.AddHook(Test); } private IntPtr Test(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case WM_COPYDATA: { COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); COPYDATASTRUCT MyKeyboardHookStruct = (COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT)); this.textbox.Text = MyKeyboardHookStruct.lpData; break; } default: { break; } } return IntPtr.Zero; }