您的位置:首页 > 其它

PostMessage()给winform窗口发送信息

2015-11-17 15:24 816 查看
背景:在解决方案中,c++实现了一个通信DLL,通信某些的状态需要转发给上层的winform窗口,在界面通过图标显示状态.

解决方案:通过发送自定义windows消息,重写winform窗口处理消息的函数。

解决流程:

1.在DLL的头文件中自定义windows消息

#define IGNITIONON_MSG  WM_USER + 1
#define IGNITIONOFF_MSG  WM_USER + 2
#define VCICONNECT_MSG WM_USER+3
#define  VCIDISCONNECT_MSG WM_USER+4


2.在winform代码文件中定义消息

public const int USER = 0x0400;//用户自定义消息的开始数值

public const int IGNITIONON_MSG = USER+1;

public const int IGNITIONOFF_MSG = USER + 2;

public const int VCICONNECT_MSG = USER + 3;

public const int VCIDISCONNECT_MSG = USER + 4;

3.向dll中传递winform句柄

BlueTooth blue = BlueTooth.GetInstance(strVciName,this.Handle);

static BlueTooth^ GetInstance(String^ strVciName,IntPtr Hwnd)
{

bool status=false;
if (nullptr == Blue)
{
Blue = gcnew BlueTooth();
status=Blue->InitEngin(strVciName);
}
else
{
status = Blue->InitEngin(strVciName);
}
if (status)
{
Blue->m_Impl->SetWindow(Hwnd.ToInt32());
return Blue;
}
else
{
return nullptr;
}

}


4.发送消息

PostMessage((HWND)pBlueTooth->m_Wnd, VCICONNECT_MSG, 0, 0);

5.重写winform窗口消息处理函数

protected override void DefWndProc(ref System.Windows.Forms.Message m)
{

switch (m.Msg)
{
case IGNITIONON_MSG:
{
}
break;
case IGNITIONOFF_MSG:
{
}
break;
case VCICONNECT_MSG:
{
}
break;
case VCIDISCONNECT_MSG:
{
}
break;
default:
base.DefWndProc(ref m);
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: