Windows消息机制

Windows系统是消息驱动的,下面这篇文章讲讲我对Windows消息机制的理解。

Window处理消息的过程:用户通过IO设备的输入操作(键盘鼠标等),看似由应用程序直接响应了用户的操作,实则不然。操作系统管理并监控着硬件设备,当键盘按下时由系统监控到,并产生一个消息(该消息记录了消息的类型,产生的窗口句柄等信息),放到系统消息队列中。系统中有一个专门的线程从消息队列中取出消息(系统是知道该消息是属于哪个窗口的),并放到该消息对应窗口的UI线程的消息队列中(UI线程有消息队列,系统为其创建。当一个线程调用了图形用户界面相关的函数时,系统会为该线程创建消息队列)。同时该UI线程应该维护一个消息循环,该消息循环会取出消息队列中的消息,并调用窗口过程去处理该消息。

关于何时为线程创建消息队列,可以参考MSDN的说明:The system does not automatically create a message queue for each thread. Instead, the system creates a message queue only for threads that perform operations which require a message queue. 

https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues

比如线程创建了窗口或者调用了GetMessage,PeekMessage,如果当前线程还没有消息队列,则系统为其创建一个。关于这两个函数的区别,上面的MSDN亦有提到(The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.)。实际上系统为该线程分配了额外的资源,用来处理用户界面相关的任务。比如THREADINFO结构,线程消息队列即包含在该结构中。除了线程的登记消息队列(posted-message queue),还有发送消息队列( send-message queue)、应答消息队列( reply-message queue)、虚拟输入队列(virtualized-input queue)、唤醒标志(wake flag)、以及用来描述线程局部输入状态的若干变量、离开代码(int nExitCode)。
 

关于THREADINFO结构,可以参考https://blog.csdn.net/whf727/article/details/6911678

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值