Winform跨进程通信

举报
清雨小竹 发表于 2022/09/25 00:36:29 2022/09/25
【摘要】 using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks; namespace 大屏Win{ ...

  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace 大屏Win
  8. {
  9. public class WinMessageHelper
  10. {
  11. private struct COPYDATASTRUCT
  12. {
  13. public IntPtr dwData;
  14. public int cbData;
  15. [MarshalAs(UnmanagedType.LPStr)]
  16. public string lpData;
  17. }
  18. //使用COPYDATA进行跨进程通信
  19. public const int WM_COPYDATA = 0x004A;
  20. [DllImport("User32.dll", EntryPoint = "SendMessage")]
  21. private static extern int SendMessage(
  22. int hWnd, // handle to destination window
  23. int Msg, // message
  24. int wParam, // first message parameter
  25. ref COPYDATASTRUCT lParam // second message parameter
  26. );
  27. [DllImport("User32.dll", EntryPoint = "FindWindow")]
  28. private static extern int FindWindow(string lpClassName, string lpWindowName);
  29. /// <summary>
  30. /// 发送消息
  31. /// </summary>
  32. /// <param name="windowReceiveTitle">接收方窗体标题名称</param>
  33. /// <param name="strData">要发送的数据</param>
  34. public static void Send(string windowReceiveTitle, string strData)
  35. {
  36. int winHandler = FindWindow(null, windowReceiveTitle);
  37. if (winHandler != 0)
  38. {
  39. byte[] sarr = System.Text.Encoding.Default.GetBytes(strData);
  40. int len = sarr.Length + 1;
  41. COPYDATASTRUCT cds;
  42. cds.dwData = (IntPtr)100;
  43. cds.lpData = strData;
  44. cds.cbData = len;
  45. SendMessage(winHandler, WM_COPYDATA, 0, ref cds);
  46. }
  47. }
  48. /// <summary>
  49. /// 接收消息
  50. /// </summary>
  51. /// <example>
  52. /// 在窗体中覆盖接收消息函数
  53. /// protected override void DefWndProc(ref System.Windows.Forms.Message m)
  54. /// {
  55. /// switch(m.Msg)
  56. /// {
  57. /// case WinMessageHelper.WM_COPYDATA:
  58. /// string str = WinMessageHelper.Receive(ref m);
  59. /// break;
  60. /// default:
  61. /// base.DefWndProc(ref m);
  62. /// break;
  63. ///
  64. /// }
  65. /// }
  66. /// </example>
  67. /// <returns>接收的到数据</returns>
  68. public static string Receive(ref System.Windows.Forms.Message m)
  69. {
  70. COPYDATASTRUCT cds = new COPYDATASTRUCT();
  71. Type cdsType = cds.GetType();
  72. cds = (COPYDATASTRUCT)m.GetLParam(cdsType);
  73. return cds.lpData;
  74. }
  75. }
  76. }

 

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/115908192

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。