8

How to get the window ID of the focus(active) window in Hex ?

Maythux
  • 82,867
  • 54
  • 239
  • 271
Johny Arduino
  • 81
  • 1
  • 2

3 Answers3

9

Try this hack:

wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 | \
    awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')

For example:

$ wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 | \
>     awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')

0x07600006  0 19051  maythuxPC Gnome Terminal

0x07600006 is the hex of active window which is the terminal in my case.

To be sure let's get it in decimal:

$ xdotool getactivewindow 
123731974

Now convert from decimal to hex:

$ printf 0x%x 123731974
0x7600006

It's the same.

Maythux
  • 82,867
  • 54
  • 239
  • 271
  • Dear Maythux thank you for your fast reply. May I ask how can I receive only the hex ID , in order to use it inside my c++ program? – Johny Arduino Jul 10 '15 at 11:41
  • Please change your code `sed 's/^0x/0x0/'` to `xargs printf "0x%08x"`. It has a bug when the hexadecimal is rounded down when it begins with `0x00`. – Iacchus Feb 11 '22 at 03:29
  • Why do we need `sed 's/^0x/0x0/'` or `xargs printf "0x%08x"`? – Ahmad Ismail Jul 31 '22 at 06:34
1

Gives you 3 seconds time to change the window focus and
prints afterwards the hexadecimal PID:

~$ sleep 3; printf 0x%x $(xdotool getactivewindow getwindowpid)
PatrickSteiner
  • 171
  • 1
  • 7
0

Use printf to convert decimal to hex. Eg. to get the window id of active window in hex use

xdotool getactivewindow | xargs -I{} printf '%x\n' {}