monitor active window and its pid using X11 lib
// monitor active window and its pid using X11 lib | |
// compile hint: install xlib-dev and then use g++ ./xxx.cpp -lX11 | |
#include <X11/Xlib.h> | |
#include <cstring> | |
#include <iostream> | |
#define MAXSTR 1000 | |
using namespace std; | |
Display *display; | |
unsigned char *prop; | |
void check_status(int status, Window window) | |
{ | |
if (status == BadWindow) | |
{ | |
printf("window id # 0x%lx does not exists!\n", window); | |
} | |
if (status != Success) | |
{ | |
printf("XGetWindowProperty failed!\n"); | |
} | |
} | |
unsigned char *get_string_property(const char *property_name, Window window) | |
{ | |
if (window == 0) | |
return 0; | |
Atom actual_type, filter_atom; | |
int actual_format, status; | |
unsigned long nitems, bytes_after; | |
filter_atom = XInternAtom(display, property_name, True); | |
status = XGetWindowProperty(display, window, filter_atom, 0, MAXSTR, False, AnyPropertyType, | |
&actual_type, &actual_format, &nitems, &bytes_after, &prop); | |
check_status(status, window); | |
return prop; | |
} | |
unsigned long get_long_property(const char *property_name, Window window) | |
{ | |
if (window == 0) | |
return 0; | |
get_string_property(property_name, window); | |
unsigned long long_property = static_cast<unsigned long>(prop[0] + (prop[1] << 8) + (prop[2] << 16) + (prop[3] << 24)); | |
return long_property; | |
} | |
unsigned long getActiveWindowPID(Window root_window) | |
{ | |
unsigned long window; | |
window = get_long_property("_NET_ACTIVE_WINDOW", root_window); | |
return get_long_property(("_NET_WM_PID"), window); | |
} | |
char *getActiveWindowName(Window root_window) | |
{ | |
unsigned long window; | |
window = get_long_property("_NET_ACTIVE_WINDOW", root_window); | |
get_string_property("_NET_WM_NAME", window); | |
return reinterpret_cast<char *>(prop); | |
} | |
int main() | |
{ | |
Display *d; | |
Window w; | |
XEvent e; | |
d = XOpenDisplay(0); | |
if (!d) | |
{ | |
cerr << "Could not open display" << endl; | |
return 1; | |
} | |
display = d; | |
w = DefaultRootWindow(d); | |
XSelectInput(d, w, PropertyChangeMask); | |
pid_t window_pid; | |
window_pid = getActiveWindowPID(w); | |
if (window_pid != 0) | |
{ | |
cout << "Active Window Name: " << getActiveWindowName(w); | |
cout << " , PID: " << window_pid << endl; | |
} | |
for (;;) | |
{ | |
XNextEvent(d, &e); | |
if (e.type == PropertyNotify) | |
{ | |
if (!strcmp(XGetAtomName(d, e.xproperty.atom), "_NET_ACTIVE_WINDOW")) | |
{ | |
window_pid = getActiveWindowPID(w); | |
if (window_pid != 0) | |
{ | |
cout << "Active Window Name: " << getActiveWindowName(w); | |
cout << " , PID: " << window_pid << endl; | |
} | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment