Windows是个基于消息映射的系统,写程序当然就得处理处理了,消息映射还有一个好处是,消息队列不用维护,Windows自己管了,呵呵,省事啊~~~
1.比较快的方法是重载TApplication的OnMessage方法
例:void __fastcall TForm1::MyOnMessage(tagMSG &Msg, bool &Handled)
{
TMessage Message;
switch (Msg.message)
{
case WM_KEYDOWN:
Message.Msg = Msg.message;
Message.WParam = Msg.wParam;
Message.LParam = Msg.lParam;
MessageDlg("你按了一个键啊!", mtWarning, TMsgDlgButtons() << mbOK, 0);
Handled = true;
break;
}
}
void __fastcall TForm1::FormCreate(TObject *Sender)
{
Application->OnMessage = MyOnMessage;
}
2.在.h中添加:
public:
void COPYDATA(TMessage & msg);
protected:
BEGIN_MESSAGE_MAP
VCL_MESSAGE_HANDLER(WM_COPYDATA, TMessage, COPYDATA)
END_MESSAGE_MAP(TForm)
在.CPP中:
void TFormS::COPYDATA(TMessage &msg)
{
if(msg.Msg==WM_COPYDATA)
{
COPYDATASTRUCT *pCDS = (COPYDATASTRUCT *)msg.LParam; //得到命令的详细内容
int msgcmd=pCDS->dwData;//得到命令的类型
int msglen=pCDS->cbData;//得到命令的长度;
if(msglen>0)
{
char *data=new char[msglen];
memcpy(data,pCDS->lpData,msglen);//命令的详细内容
处理data吧
}
}
}
自己发送消息时:
int server_var_table::sendmsg2ui(String msgs,int msgcmd)//发送消息到主窗口,通知主窗口修改控件
{
HWND h=FormS->Handle;
int msglen=msgs.Length()+1;
char *msg = new char[msglen];
memcpy(msg,msgs.c_str(),msglen);
COPYDATASTRUCT cs;
cs.dwData = msgcmd; //表示通知消息的类型
cs.cbData = msglen;
cs.lpData = msg;
int x= SendMessage(h,WM_COPYDATA,(WPARAM)h,(LPARAM)(&cs));
delete []msg;
return x;
}
呵呵,搞定,收工先。