我可以在 Windows 中使用自己的消息循环吗?
我正在 Windows 上使用 Visual Studio 构建 C++ 程序。它依赖于 COM 基础 API,发送 Windows 消息以进行通知。
要处理这些消息,我看到两种可能性:
- 创建一个 Windows 窗体并在其上调用 doModal 来处理消息,但由于我不想使用任何 UI,因此我不想做
- 自己的循环来处理消息消息
我不知道什么是最好的,或者是否有另一种方法来处理消息(可能有一个可以启动循环的Windows函数)
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
I am building a C++ program, on windows, using Visual Studio. It relies on a COM base API, that sends windows message for notification.
To process those messages, I see two possibilities:
- Create a windows form and call doModal on it which should process the messages, but since I don't want to use any UI, it's not what I want to do
- make my own loop for processing messages
I don't know what is best, or if there is another way to process the messages (there is probably a windows function that can launch the loop)
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不仅仅是为了您自己的利益,COM要求您创建一个消息循环。 COM 需要它来处理单元线程 COM 服务器,这是一个昂贵的词,表示“不支持多线程的组件”。他们中的绝大多数人没有。
最好创建一个窗口,它不必是可见的。这为您提供了一个可以在 SendMessage() 调用中使用的 HWND。您编写的窗口过程可以处理这些消息。从这里开始,创建一个最小的用户界面就变得很容易,例如使用 Shell_NotifyIcon。当出现问题时可以显示通知,这总是很好。比日志中无人查看的事件要好得多。
It is not just for your own benefit, COM requires you to create a message loop. COM needs it to handle apartment threaded COM servers, an expensive word for "components that don't support multi-threading". The vast majority of them don't.
It is best to create a window, it doesn't have to be visible. That gives you a HWND that you can use in your SendMessage() calls. The window procedure you write can process the messages. From there, it gets to be easy to create a minimal user interface, with Shell_NotifyIcon for example. Always nice when you can display a notification when something goes wrong. So much better then an event in a log that nobody ever looks at.
是的,你可以。每个线程都可以有一个消息循环,并且您不需要任何窗口来接收或发送消息(请参阅
PostThreadMessage
)。如果您的应用程序是事件驱动的,那么使用此方法没有任何问题。
Yes, you can. Every thread can have one message loop and you don't need any windows to receive messages or send them (see
PostThreadMessage
).There is nothing wrong with using this method if your application is event-driven.