Skip to content

Instantly share code, notes, and snippets.

@lmas
Created February 25, 2017 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmas/19e6ea1caa3248846d0a784ae54e8917 to your computer and use it in GitHub Desktop.
Save lmas/19e6ea1caa3248846d0a784ae54e8917 to your computer and use it in GitHub Desktop.
Get the title of the currently active window in linux
package main
import (
"fmt"
"os/exec"
"strings"
"time"
)
func main() {
for {
t, err := ActiveWindowTitle()
if err != nil {
panic(err)
}
fmt.Println(t)
time.Sleep(1 * time.Second)
}
}
func ActiveWindowTitle() (string, error) {
// Grab the ID of the current active window
out, err := exec.Command("xprop", "-root", "_NET_ACTIVE_WINDOW").Output()
if err != nil {
return "", err
}
parts := strings.Split(string(out), " ")
if len(parts) != 5 {
return "", fmt.Errorf("unexpected output from xprop -root _NET_ACTIVE_WINDOW: %s", string(out))
}
id := parts[4]
// Grab the title of the current active window, using ID
out, err = exec.Command("xprop", "-id", id, "WM_NAME").Output()
if err != nil {
return "", err
}
parts = strings.Split(string(out), "=")
if len(parts) != 2 {
return "", fmt.Errorf("unexpected output from xprop -id ID WM_NAME: %s", string(out))
}
return strings.Trim(strings.TrimSpace(parts[1]), `"`), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment