Created
February 25, 2017 13:56
-
-
Save lmas/19e6ea1caa3248846d0a784ae54e8917 to your computer and use it in GitHub Desktop.
Get the title of the currently active window in linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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