This method is suitable if you are using a console program and also want to handle some global shortcuts.
Not creating a window here means not creating a visible window
Using MessageOnly windows
There is a special window handle HWND_MESSAGE in Windows, its value is -3, when a window's parent window is it, this window will become a "message-only window"
Messages can be sent and received using the message-only window. It is invisible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window just dispatches messages.
To create a message-only window, specify the HWND_MESSAGE constant or the handle of an existing message-only window in the hWndParent parameter of the CreateWindowEx function. You can also change an existing window to a message-only window by specifying HWND_MESSAGE in the hWndNewParent parameter of the SetParent function.
Reference: Window Features: Message Windows Only - Win32 apps | Microsoft Learn
Example usage of WPF:
// 窗口创建的参数
HwndSourceParameters hwndSourceParameters =
new HwndSourceParameters()
{
HwndSourceHook = Hook,
ParentWindow = (IntPtr)(-3), // a magic window handle
};
// 创建窗口
hwndSource =
new HwndSource(hwndSourceParameters);
// Hook 消息方法定义
IntPtr Hook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// 这里处理消息
}