See SetWindowsHookEx API function with the first parameter equal to WH_MOUSE or WH_MOUSE_LL to determine a window under the cursor. If it’s not your window your can use the same function to set another hook to that window to monitor/filter messages. This hook must look for the WM_SETCURSOR and WM_GETCURSOR messages.
The simplest way is to capture mouse input (SetCapture api), you can see how it’s working in Image Selector when you’re dragging an image outside the window: demo1.exe->Enable drag’n’drop-drag an image from the right pane.
If the mouse cursor is over a window created by another thread, the system will direct mouse input to the specified window only if a mouse button is down.
Outside of the drag-n-drop functionality SetCapture has a little sense.