您的位置:首页 > 编程语言

我在BCB中实现消息处理的简单代码--XJQ2003

2008-11-05 15:33 411 查看
一-//初始化

void INITMessage(HWND pWnd,UINT uMsgID)

{

pWnd= Form1->Handle;
uMsgID=WM_FILEREADY;
pWnd=FindWindow("TForm1","Form1");//这个好象可以不要
if(pWnd==NULL)
return;

}

二、//接受和处理消息

1,首先在头文件里定义个函数

class TForm1 : public TForm
{
__published: // IDE-managed Components
void __fastcall FormCreate(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
void __fastcall AppMessage(tagMSG &Msg, bool &Handled);//就是这个函数

};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;

2,在ONCREAT事件中加上

void __fastcall TForm1::FormCreate(TObject *Sender)
{
Application->OnMessage = AppMessage;

}

3,在AppMessage处理消息

void __fastcall TForm1::AppMessage(tagMSG &Msg, bool &Handled)
{
String ss;
if (Msg.message == WM_FILEREADY)
{
ss="收到消息:"+IntToStr(Msg.wParam);
Memo1->Lines->Add(ss);
Handled = true;
}
/* for all other messages, Handled remains False so that other message handlers can respond */
}

三、消息发送

void SendMyMsg(unsigned int wParam)
{

HWND MypWnd;
UINT MyMsgID;

//------消息句柄有效判断---------
MypWnd=pWnd;
MyMsgID=uMsgID;
if(pWnd==NULL) return -3;
if(uMsgID<=1024)return -4;
try
{
PostMessage(MypWnd,MyMsgID,wParam,0);
}
catch(...)
{
}
}

/*

BOOL PostMessage(

HWND hWnd, // handle of destination window
UINT Msg, // message to post
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);

Parameters

hWnd

Identifies the window whose window procedure is to receive the message. Two values have special meanings:

Value Meaning
HWND_BROADCAST The message is posted to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows. The message is not posted to child windows.
NULL The function behaves like a call to PostThreadMessage with the dwThreadId parameter set to the identifier of the current thread.

Msg

Specifies the message to be posted.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

*/

正个过程比较简单,因为我实现的功能也比较少,就是简单的发送消息和接受处理消息数据。要感谢网友的帮助,使我更好更轻松的工作,学习更多的知识。

如果要截获所有的键盘消息,可以这样:
void __fastcall TForm1::AppMessage(tagMSG &Msg, bool &Handled)
{
if(Msg.Message == WM_KEYDOWN)
{
switch(Msg.CharCode)
{
case VK_F1:
break;
default:
break;
}
}
Handle = false;
}
然后在Form的OnCreate事件中写如下代码:
Application->OnMessage = AppMessage;
这样就能收到键盘的消息了,case后面跟的就是按键的虚拟表的其中一个,它代表你按下了F1键,其余的自己查帮助好了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: