title: How to programatically get an OSX window id from a process id on 10.6? (using Applescript, Objective-C, whatever)
body: <p>I know that I can do</p>
  
  <pre><code>tell application "Safari" to id of window 1
  </code></pre>
  
  <p>to get the window ID of Safari. However, this only works for Applescriptable applications. I want to be able to write a program that will take a PID as input and output the window ID. (In case you are curious, this will be used in turn to supply the window ID to the undocumented "CGSMoveWorkspaceWindowList" to move applications between spaces on 10.6.)</p>
  
  <p>According to <a href="https://stackoverflow.com/questions/6178860/getting-window-number-through-osx-accessibility-api">this</a> question, it is possible to do it via undocumented APIs in the OSX Accessibility API with Objective-C. Unfortunately, the author didn't specify any additional information about it.</p>
  
  <p>Of course, I'm not married to Objective-C, I just want to get the WID from a PID by any means possible. One other possibility, if anyone knows how, is to get the WID from the currently activated/frontmost process (I have a command line tool to activate a given PID).</p>
  
  <p>Edit: Thanks to weichsel pointing me down the right path, I made a program to output all window data.</p>
  
  <pre><code>#include &lt;Carbon/Carbon.h&gt;
  
  // compile as such:
  //  gcc -framework carbon -framework foundation GetWindowList.c
  
  int main(int argc, char **argv) {
  
      CFArrayRef windowList;
  
      if (argc != 1) {
          printf("usage: %s\n", argv[0]);
          exit(1);
      }
  
      windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);
      NSLog(CFSTR("Array: %@"), windowList);
      CFRelease(windowList);
  
  }
  </code></pre>
  
  <p>Then, I used Python to parse all of the data, mostly because I have 0 idea on how to do that in Objective-C, and Python would probably be less lines of code anyway. =D</p>
  
  <pre><code>import os
  import re
  
  PID_WID_List = []
  temp = os.popen('./GetWindowList 2&gt;&amp;1').read().strip().split('},')
  for i in temp:
      match = re.search('kCGWindowOwnerPID = (\d+);', i)
      pid = match.group(1)
      match = re.search('kCGWindowNumber = (\d+);', i)
      wid = match.group(1)
      PID_WID_List.append((pid, wid))
  </code></pre>
  
  <p>Note that NSLog writes everything to system.log, so this method isn't suitable for an infinite checking loop.</p>
  
  <p>Thanks again to weichsel.</p>