Skip to content

Instantly share code, notes, and snippets.

Created July 3, 2015 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/6df3c14250833ed40484 to your computer and use it in GitHub Desktop.
Save anonymous/6df3c14250833ed40484 to your computer and use it in GitHub Desktop.
// 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 <string>
class WindowsMatchingPid
{
public:
WindowsMatchingPid(Display *display, Window wRoot, std::string name )
: _display(display)
, _name(name)
{
// Get the PID property atom.
_atomPID = XInternAtom(display, "_NET_WM_NAME", True);
if(_atomPID == None)
{
std::cout << "No such atom" << std::endl;
return;
}
search(wRoot);
}
const std::list<Window> &result() const { return _result; }
private:
Atom _atomPID;
Display *_display;
std::list<Window> _result;
std::string _name;
void search(Window w)
{
// Get the PID for the current Window.
Atom type;
Atom utf8Atom = XInternAtom( _display, "UTF8_STRING", false );
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *retName = 0;
if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, utf8Atom,
&type, &format, &nItems, &bytesAfter, &retName))
{
if(retName && std::string((char*)retName) == _name )
{
std::cout << "got temp name: " << retName << std::endl;
std::cout << "window id = : " << w << std::endl;
// If the PID matches, add this window to the result set.
//if( 0 == strcmp( _name.c_str(), (char*)retName ) )
// _result.push_back(w);
XFree(retName);
}
}
// 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]);
}
}
};
// USE IT LIKE THIS
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "windowId.h"
#include <QVBoxLayout>
#include <QTimer>
#include <QWindow>
#include <QProcess>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto pid( 18830 );
// Start with the root window.
Display *display = XOpenDisplay(0);
// find the window whose name is "view", print its window ID
WindowsMatchingPid match(display, XDefaultRootWindow(display), "view");
// Print the result, should only get one
const std::list<Window> &result = match.result();
for(std::list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
std::cout << "Window #" << (unsigned long)(*it) << std::endl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment