Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

linux - Getting pid and details for topmost window

Does anyone know how to get the PID of the top active window and then how to get the properties of the window using the PID? I mean properties like process name, program name, etc.

I'm using Qt under Linux (Ubuntu 9.10).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

there is a command in linux call xprop which is a utility for displaying window properties in an X server. In linux xprop -root gives you the root windows properties and also other active programs. then you can get the ID of the active window using this command:

xprop -root | grep _NET_ACTIVE_WINDOW(WINDOW)

to get just the active window ID ( without "_NET_ACTIVE_WINDOW(WINDOW): window id # " in the beginning of the line ) use this command:

xprop -root | awk '/_NET_ACTIVE_WINDOW(WINDOW)/{print $NF}'

now you can save this command output in a user defined variable:

myid=xprop -root | awk '/_NET_ACTIVE_WINDOW(WINDOW)/{print $NF}'

xprop have an attribute call -id. This argument allows the user to select window id on the command line. We should look for _NET_WM_PID(CARDINAL) in output ... so we use this command:

xprop -id $myid | awk '/_NET_WM_PID(CARDINAL)/{print $NF}'

this gives you the topmost active window process ID.

to be more trickey and do all things in just 1 command ... :

 xprop -id $(xprop -root | awk '/_NET_ACTIVE_WINDOW(WINDOW)/{print $NF}') | awk '/_NET_WM_PID(CARDINAL)/{print $NF}'

Now I can run these commands via my C++ program ( in linux ) using popen function, grab stdout and print or save it. popen creates a pipe so we can read the output of the program we are invoking.

( you can also use '/proc' file system and get more detail of a PID ('/proc/YOUR_PID/status') )

#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;

inline std::string exec(char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
                result += buffer;
    }
    pclose(pipe);
    return result;
}

int main()
{
    //we uses \ instead of  (  is a escape character ) in this string
 cout << exec("xprop -id $(xprop -root | awk '/_NET_ACTIVE_WINDOW\(WINDOW\)/{print $NF}') | awk '/_NET_WM_PID\(CARDINAL\)/{print $NF}'").c_str(); 
 return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...