Here's some more functions:

version(linux)
string getProcessCommandLine(long pid) {
        import std.file;
        import std.conv;
        return readText("/proc/" ~ to!string(pid) ~ "/cmdline");
}


And for looking at windows, you'll want my simpledisplay.d and color.d from here:
https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff


Then use these two functions:

import simpledisplay;
Window getActiveWindow() {
        auto display = XDisplayConnection.get();
        auto focusedAtom = GetAtom!"_NET_ACTIVE_WINDOW"(display);

        Atom target;
        int format;
        arch_ulong bytesafter, length;
        char* value;
        XGetWindowProperty(
                display,
                RootWindow(display, DefaultScreen(display)),
                focusedAtom,
                0,
                100000 /* length */,
                false,
                0 /*AnyPropertyType*/,
                &target, &format, &length, &bytesafter, &value);

        assert(format == 32);

        auto activeWindowId = *cast(uint*) value;

        XFree(value);

        return cast(Window) activeWindowId;
}

long getWindowPid(Window w) {
        auto display = XDisplayConnection.get();
        auto atom = GetAtom!"_NET_WM_PID"(display);

        Atom target;
        int format;
        arch_ulong bytesafter, length;
        char* value;
        XGetWindowProperty(
                display,
                w,
                atom,
                0,
                100000 /* length */,
                false,
                0 /*AnyPropertyType*/,
                &target, &format, &length, &bytesafter, &value);

        long pid;

        if(format == 32)
                pid = *cast(uint*) value;
        if(format == 64)
                pid = *cast(long*) value;

        XFree(value);

        return pid;
}



(You might notice they are substantially similar... perhaps I'll add a generic wrapper of some sort to simpledisplay.d for this stuff.)


Then you can use it:

void main() {
        auto activeWindow = getActiveWindow();
        auto pid = getWindowPid(activeWindow);
        writeln(pid);
        if(pid)
                writeln(getProcessCommandLine(pid));
}


pid might not be available, so be sure to check that it is non-zero before trying to use it.

But I compiled this program:

dmd processes.d simpledisplay.d color.d

And ran it:

$ sleep 2; ./processes
9412
/home/me/firefox9/firefox/firefox


(The sleep was to give me a chance to focus another window before the program ran, here I went to firefox and it successfully showed that, or xterm if I go there, and so on. My rxvt does not set this property though... nor does my own simpledisplay.d windows!)



Anywho this is linux/X11 code, if you version them out you should be able to make a generic Windows function too.

Reply via email to