title: Uniquely identify active window on OS X
body: <p>I’m trying to patch <a href="http://code.google.com/p/shiftit/" rel="noreferrer">an application</a> that resizes windows using the accessibility API.</p>
  
  <p>I need to maintain a dictionary with the previous sizes of windows. The key needs to identify the currently active window. At the moment, this active window is retrieved via <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Protocols/NSAccessibility_Protocol/Reference/Reference.html#//apple_ref/doc/c_ref/NSAccessibilityFocusedWindowAttribute" rel="noreferrer"><code>NSAccessibilityFocusedWindowAttribute</code></a> upon the press of a hotkey.</p>
  
  <p>However, every time this method is called, the returned <code>AXUIElementRef</code> which identifies the window <em>is different</em>! This of course means that I cannot use it as a dictionary key – the dictionary won’t find the corresponding entry.</p>
  
  <p>The following code reproduces the problem:</p>
  
  <pre><code>-(IBAction)testWindowIdentification:(id)sender{
      AXUIElementRef focusedApp;
      AXUIElementRef focusedWindow;
  
      AXUIElementCopyAttributeValue(_systemWideElement,
                                    (CFStringRef) kAXFocusedApplicationAttribute,
                                    (CFTypeRef*) &amp;focusedApp);
      AXUIElementCopyAttributeValue((AXUIElementRef) focusedApp,
                                    (CFStringRef) NSAccessibilityFocusedWindowAttribute,
                                    (CFTypeRef*) &amp;focusedWindow);
      CFShow(focusedWindow);
  }
  </code></pre>
  
  <p><code>_systemWideElement</code> has been initialised in the <code>init</code> method using a call to <code>AXUIElementCreateSystemWide()</code>.</p>
  
  <p>The <code>CFShow</code> statement clearly shows different IDs every time the method is called (even though the same window is active), which is useless for me:</p>
  
  <pre><code>&lt;AXUIElement 0x47e850&gt; {pid=42463}
  &lt;AXUIElement 0x47e890&gt; {pid=42463}
  &lt;AXUIElement 0x47e2c0&gt; {pid=42463}
  …
  </code></pre>
  
  <p>The <a href="http://developer.apple.com/library/mac/#documentation/Accessibility/Reference/AccessibilityLowlevel/AXUIElement_h/" rel="noreferrer">documentation on <code>AXUIElement</code></a> shows no method that retrieves a unique attribute for the UI element, and neither does <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Protocols/NSAccessibility_Protocol/Reference/Reference.html" rel="noreferrer">that of the <code>NSAccessibility</code> protocol</a>.
  The unique PID is <em>not</em> enough for me, since a process can have multiple windows.</p>
  
  <p><strong>How can I retrieve some unique identifier of the active window in Cocoa?</strong></p>
  
  <p>(By the way, the real code is checking the return codes in the above calls; there is no error, the calls succeed.)</p>