Get current active window's title in Java

前端 未结 6 2025
耶瑟儿~
耶瑟儿~ 2020-12-08 17:43

I am trying to write a Java program that logs what application I\'m using every 5 seconds (this is a time tracker app). I need some way to find out what the current active w

6条回答
  •  天命终不由人
    2020-12-08 18:26

    I have written a java program using user361601's script. I hope this will help others.

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class WindowAndProcessInfo4Linux {
    
    public static final String WIN_ID_CMD = "xprop -root | grep " + "\"_NET_ACTIVE_WINDOW(WINDOW)\"" + "|cut -d ' ' -f 5";
    public static final String WIN_INFO_CMD_PREFIX = "xwininfo -id ";
    public static final String WIN_INFO_CMD_MID = " |awk \'BEGIN {FS=\"\\\"\"}/xwininfo: Window id/{print $2}\' | sed \'s/-[^-]*$//g\'";
    
    public String execShellCmd(String cmd){
        try {  
    
            Runtime runtime = Runtime.getRuntime();  
            Process process = runtime.exec(new String[] { "/bin/bash", "-c", cmd });  
            int exitValue = process.waitFor();  
            System.out.println("exit value: " + exitValue);  
            BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));  
            String line = "";  
            String output = "";
            while ((line = buf.readLine()) != null) {
                output = line;
            }
            return output;
        } catch (Exception e) {  
            System.out.println(e);
            return null;
        }  
    }
    
    public String windowInfoCmd(String winId){
        if(null!=winId && !"".equalsIgnoreCase(winId)){
            return WIN_INFO_CMD_PREFIX+winId +WIN_INFO_CMD_MID;
        }
        return null;
    }
    
    public static void main (String [] args){
        WindowAndProcessInfo4Linux windowAndProcessInfo4Linux = new WindowAndProcessInfo4Linux();
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String winId = windowAndProcessInfo4Linux.execShellCmd(WIN_ID_CMD);
        String winInfoMcd = windowAndProcessInfo4Linux.windowInfoCmd(winId);
        String windowTitle = windowAndProcessInfo4Linux.execShellCmd(winInfoMcd);
        System.out.println("window title is: "+ windowTitle);
    
    }
    }
    

    // the thread.sleep is there so that you get time to switch to other window :) also, you may use quartz from spring to schedule it.

提交回复
热议问题