How to listen for Windows broadcast messages in .NET?

假装没事ソ 提交于 2019-12-05 10:11:49

I assume that the examples you gave were merely that: examples. Because a number of those have managed equivalents that already wrap all of this for you. Like WM_POWERBROADCAST is wrapped by the Microsoft.Win32.SystemEvents.PowerModeChanged event. And WM_SETTINGCHANGED is equivalent to Microsoft.Win32.SystemEvents.UserPreferenceChanged.

Anyway, broadcasted messages like those you describe are sent to all top-level windows, so all you really need to do is create a top-level window and override its WndProc method to process the notification messages that you're interested in.

Use the NativeWindow class to make things easy on yourself. In this case, you don't need everything that is provided by the Form class, all you need is something to wrap CreateWindowEx and provide a window procedure. Just create the window without the WS_VISIBLE flag because you don't want it appearing on the screen.

The .NET Framework does this all over the place internally. For example, the internal TimerNativeWindow class used for System.Windows.Forms.Timer. If you want to check out the implementation for yourself in Reflector, start looking there. You should be able to search for constants, but drilling down into a hierarchy of classes for which you know there must be such a notification message handled internally is generally a smarter way to search. The SystemEvents class (discussed above) is also a good place to start looking for implementation strategies.

Do note that you can't use a message-only window here (HWND_MESSAGE) because they won't receive broadcast events. The TimerNativeWindow that I mentioned above does do that, because it doesn't care about broadcast events, so don't just copy and paste the code from there!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!