DLL(MFC)通过Window消息向C#程序传递数据

来源:互联网 发布:网络图片可爱搞笑带字 编辑:程序博客网 时间:2024/05/17 09:07

      这是我在用C#开发IOServer遇到的一个问题,该程序需要用到原先用MFC开发的DLL,最大问题是该dll运行过程中的一些信息,通过window消息向指定的hwnd(窗体句柄)发送数据。数据的指针放在WParam参数里,LParam参数是数据的类型信息。

     C#提供  m.GetLParam()函数,可惜我的数据放在WParam参数里(这个还不能修改,否则原有程序就无法运行了,修改的代价太高),所以这个函数不能用。

    下面经过多次测试,终于获取数据成功。

   MFC DLL中的相关代码:

   TCHAR cMessage[255];
  SYSTEMTIME stime;
     GetLocalTime(&stime);
   swprintf(cMessage,_T("%04d-%02d-%02d %02d:%02d:%02d [%-16s #%03d] - %s "),stime.wYear,stime.wMonth,stime.wDay,stime.wHour,stime.wMinute,stime.wSecond,strSource,lngNO,strMessage);
        if (G_IOMRun.lngMsgFlag==0)
  {
      SendMessage(G_IOMRun.Hwnd, WM_USER+7722,(long)cMessage,lngType); //
  }

  在C#中需要重载窗体的消息处理函数,相关代码如下:

      [DllImport("kernel32", EntryPoint = "CopyMemory")]
        public static extern void CopyMemory(StringBuilder Destination,IntPtr Source,int Length);
        ///


        /// 重载窗口函数
        ///

        ///
        protected override void WndProc(ref Message m)
        {
            //---------------------
            if(m.Msg == 0x0400 + 7722)
            {             
               StringBuilder strData = new StringBuilder(255);
               CopyMemory(strData, m.WParam, 255);
               ShowInfo((int)m.LParam,strData.ToString());
            }
            //---------------------
            base.WndProc(ref m);
        }

注意:CopyMemory函数的声明需要自己修改(原声明如下),一定要去掉“ref” 关键字,否则会获取不正确。

[DllImport("kernel32", EntryPoint="CopyMemory")]
public static extern void CopyMemory (
        ref int Destination,
        ref int Source,
        int Length
);

 

 




原创粉丝点击