.NET Compact Framework下的进程间通信之一 --Windows Message

转帖|其它|编辑:郝浩|2009-03-17 10:21:11.000|阅读 717 次

概述:在Wince和Windows Moblie 下的进程间通信的技术实现方法。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

在Wince和Windows Moblie 下的进程间通信可以由以下几种技术实现。

1. Windows Message

2. Point-to-Point Message Queues

3. MSMQ

下面使用讲述.NET Compact Framework下使用Windows Message进行进程间的通信。

引用库

在CF.net下进行Windows Message的开发需要引用Microsoft.WindowsCE.Forms,该DLL一般存放于C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE\Microsoft.WindowsCE.Forms.dll

发送消息

using Microsoft.WindowsCE.Forms;

public partial class MsgForm : Form
{
        [DllImport(
"coredll.dll", EntryPoint = "RegisterWindowMessage", SetLastError = true)]
        
private static extern uint RegisterWindowMessage(string lpString);
        
private uint msgUid = RegisterWindowMessage("MESSAGE_UID");

   public static int MSG_BROADCAST = 0xFFFF;
   
   private
 void SendMessage(object sender)
        {
            Message msg 
= Message.Create((IntPtr)MSG_BROADCAST, (int)msgUid , IntPtr.Zero, IntPtr.Zero);
            MessageWindow.SendMessage(
ref msg);
        }

}

首先需要P/Invoke RegisterWindowMessage 函数,每个发送的message都有唯一的UID,这样接收方才能根据UID进行监听和接收该Message。

发送之前先create一个Message对象,参数一为接收对象,如果为进程间通信可以使用广播的形式(MSG_BROADCAST),第二个参数为message的UID,接收方利用这一表示辨别message。第三和第四分别为WParam和LParam,这是标准windows message的传递参数。

接收消息 

using Microsoft.WindowsCE.Forms;

public class MsgWindow : MessageWindow
{
    [DllImport(
"coredll.dll", EntryPoint = "RegisterWindowMessage", SetLastError = true)]
   
private static extern uint RegisterWindowMessage(string lpString);

   
private uint msgUid = RegisterWindowMessage("MESSAGE_UID");

    
protected override void WndProc(ref Message msg)
    {
       
if (msg.Msg == msgUid )
       {
           
//handle the message. 
       }
    }
}

接收消息需要定义一个继承类,继承于MessageWindow,同时他同样需要P/Invoke RegisterWindowMessage 函数,定义接收message的唯一UID。

重写WndProc,然后通过msg.Msg 来辨别关心的消息。

使用Form处理Message

如果接收方接收到message需要更新到form的话就定义一个form的reference,这样可以利用form来处理消息。其实不一定使用Form来处理message,使用Form就能比较方便的利用ui来反映message的接收和处理情况。

public partial class MsgForm : Form
{
   
private MsgWindow MsgWin;

    
public MsgForm()
    {
       
//pass the form reference to messagewindow
        this.MsgWin = new MsgWindow(this);
    }
}

public class MsgWindow : MessageWindow
{
    
private MsgForm msgForm;

  public MsgWindow(MsgForm msgForm)
     {
            
this.msgForm= msgForm;
     }

  protected override void WndProc(ref Message msg)
   {
      
if (msg.Msg == msgUid )
      {
       //call form to handle the message. 
         msgForm.HandleMsg();
     }
   }
}

MsgWindow 保存MsgForm 的引用,这样当MsgWindow 接收到消息就可以使用form来处理。


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP