欢迎莅临 SUN WU GANG 的园子!!!

世上无难事,只畏有心人。有心之人,即立志之坚午也,志坚则不畏事之不成。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  470 随笔 :: 0 文章 :: 22 评论 :: 30万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Winform to Winfrom==>

发送端==》

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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);
            }
        }
    }
}

接收端==》

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
   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 接收方:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#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;
       }

  

 

posted on   sunwugang  阅读(637)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示