X11 forwarding - grab windows of programs already running

Not really a solution to literal "grabbing windows of programs already running", but still…

Use xpra.

On X11, it is also known as screen for X11: it allows you to run programs, usually on a remote host, direct their display to your local machine, and then to disconnect from these programs and reconnect from the same or another machine, without losing any state.

[…]

Xpra also allows forwarding of sound, clipboard and printing services. Sessions can be accessed over SSH, or password protected over plain TCP sockets with or without SSL.

It has to be installed, configured and started beforehand, just like screen or tmux for console applications. You have to run your program via xpra in the first place, then you can do the magic of (re)connecting from different machines.

xpra is available as xpra package at least in Debian and Ubuntu. I have used it few times. The performance was better than for plain X forwarding.

Examples are here. The following are from man xpra on my Kubuntu:

xpra start :7

Start an xpra server using display number :7.

DISPLAY=:7 firefox

Start firefox running inside the xpra server. Run this on the host where xpra was started or in terminal forwarded by xpra. No window will appear until you attach with xpra attach.

You run the above examples on your A. Then you can attach directly from A:

xpra attach :7

Attach to the xpra server that is using local display number :7. Any apps running on that server will appear on your screen.

or from your B:

xpra attach ssh:foo@frodo:7

Use ssh to attach to the xpra server that is running on machine frodo as user foo and using display :7. Any apps running on that server will appear on your local screen.