问题描述
有谁知道如何获取顶部活动窗口的PID,然后如何使用PID获取窗口的属性?我的意思是进程名称、程序名称等属性
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.
我在 Linux (Ubuntu 9.10) 下使用 Qt.
I'm using Qt under Linux (Ubuntu 9.10).
推荐答案
linux 中有一个命令调用 xprop,它是一个用于在 X 服务器中显示窗口属性的实用程序.在 linux 中 xprop -root
为您提供根窗口属性以及其他活动程序.然后您可以使用以下命令获取活动窗口的 ID:
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)
要获取只是活动窗口 ID(在行的开头没有_NET_ACTIVE_WINDOW(WINDOW): window id #")使用以下命令:
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 有一个属性调用 -id.此参数允许用户在命令行上选择窗口 ID.我们应该在输出中寻找 _NET_WM_PID(CARDINAL) ... 所以我们使用这个命令:
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}'
这会为您提供最顶层的活动窗口进程 ID.
this gives you the topmost active window process ID.
变得更加棘手,只需 1 个命令即可完成所有事情......:
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}'
现在我可以使用 popen 函数通过我的 C++ 程序(在 linux 中)运行这些命令,获取标准输出并打印或保存它.popen 创建了一个管道,以便我们可以读取我们正在调用的程序的输出.
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.
(您也可以使用/proc"文件系统并获取更多 PID 的详细信息 ('/proc/YOUR_PID/status'))
( 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;
}
这篇关于获取最顶层窗口的 pid 和详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!