SetWindowRgn Shenanigans


Recently I did some experiments on cropping a window, to see if I can cleanly fit it into a “viewport” defined by Jwno. Along the way, I found an interesting API function: SetWindowRgn.

Warning: We’re gonna cut holes in windows in this post, and it’s going to be GRAPHIC.

So What’s a Rgn?

Rgn stands for region, which is some data structure used by windows to… define regions in a window’s client area. There’re a bunch of API functions to create and manipulate regions, such as CreateRectRgn.

Regions can be used for various purposes, and one of them is to be used in SetWindowRgn, to define where a window can draw its content. It acts like a mask: only stuff that’s drawn inside the marked area will be shown to the user. And yes, you can impolitely change the mask of a window you don’t own 🤔.

An Example

Here’s some code to cut a diamond-shaped hole in a chosen window:

(use jw32/_winuser)
(use jw32/_wingdi)

(def hwnd 0xe0732)
(def hrgn1 (CreatePolygonRgn [[300 200] [200 400] [300 600] [400 400]] WINDING))
(def hrgn2 (CreateRectRgn 0 0 10000 10000))
(CombineRgn hrgn1 hrgn2 hrgn1 RGN_DIFF)
(SetWindowRgn hwnd hrgn1 true)

If you’re going to try it out in Jwno’s REPL, remember to change hwnd to point to the window of your choice.

And it works like this:

Can It Be Used To Crop a Window?

Unfortunately, no. Not without some hacks, at least. If we move the hole near the border of a window:

You can see the thin window border is still there. That’s because the border is actually rendered by DWM (Desktop Window Manager, a compoment of Windows), just like Wayland’s server-side window decorations. Of course we can try to remove the window borders entirely, or hook the WM_NCPAINT message, but I think most windows won’t expect these hacks, and may just freak out.

And there’re these odd-ball windows (File Explorer being one of them):

Instead of the content behind the window, the hole just shows a solid backdrop. It may have something to do with the glassy backdrop effects rendered by the window. I’ll need to carry out more experiments to figure it out.

Here’s a Funny Usecase, Though

When doing the research, I came across an interesting AHK script. The script simply digs a hole in the window beneath the mouse cursor (by eventually calling SetWindowRgn), so that one can drag-n-drop stuff from places covered by that window. Pretty creative I’d say 😅.

Get Jwno

Buy Now$10.00 USD or more

Leave a comment

Log in with itch.io to leave a comment.