怎样由进程id获取X11窗口id

  • Post author:
  • Post category:其他



来源:

http://stackoverflow.com/questions/151407/how-to-get-an-x11-window-from-a-process-id

在linux下,我的C++应用需要用到 fork() 和 execv() 来启动多个OpenOffice的实例,以便查看一些幻灯片放映。这是其中一部分工作。

接下来,我希望能移动OpenOffice的窗口到屏幕上的特定位置。我可以用XMoveResizeWindow()函数做到这一点,但是我需要找到每个实例的窗口。

我有每个实例的进程ID,怎样能找到他们对应的窗口?

// Attempt to identify a window by name or attribute.
// by Adam Pierce <adam@doctort.org>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>
#include <stdlib.h>

using namespace std;

class WindowsMatchingPid
{
public:
    WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
    	: _display(display)
    	, _pid(pid)
    {
    // Get the PID property atom.
    	_atomPID = XInternAtom(display, "_NET_WM_PID", True);
    	if(_atomPID == None)
    	{
    		cout << "No such atom" << endl;
    		return;
    	}

    	search(wRoot);
    }

    const list<Window> &result() const { return _result; }

private:
    unsigned long  _pid;
    Atom           _atomPID;
    Display       *_display;
    list<Window>   _result;

    void search(Window w)
    {
    // Get the PID for the current Window.
    	Atom           type;
    	int            format;
    	unsigned long  nItems;
    	unsigned long  bytesAfter;
    	unsigned char *propPID = 0;
    	if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
    	                                 &type, &format, &nItems, &bytesAfter, &propPID))
    	{
    		if(propPID != 0)
    		{
    		// If the PID matches, add this window to the result set.
    			if(_pid == *((unsigned long *)propPID))
    				_result.push_back(w);

    			XFree(propPID);
    		}
    	}

    // Recurse into child windows.
    	Window    wRoot;
    	Window    wParent;
    	Window   *wChild;
    	unsigned  nChildren;
    	if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
    	{
    		for(unsigned i = 0; i < nChildren; i++)
    			search(wChild[i]);
    	}
    }
};

int main(int argc, char **argv)
{
    if(argc < 2)
    	return 1;

    int pid = atoi(argv[1]);
    cout << "Searching for windows associated with PID " << pid << endl;

// Start with the root window.
    Display *display = XOpenDisplay(0);

    WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);

// Print the result.
    const list<Window> &result = match.result();
    //for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
    	//cout << "Window #" << (unsigned long)(*it) << endl;
    cout << "Window id: "<< (unsigned long)(*result.begin()) << endl;

    return 0;
}

//编译:g++ -o xx this.cpp -lX11