Question: I'm trying to use the accessibility API to get the active window, the problem is when I try to get the focused application I get a cannot complete error. Below is a small piece of my code:

```
AXUIElementRef systemElement =
    AXUIElementCreateSystemWide();

AXUIElementRef focused = nullptr;
AXError error = AXUIElementCopyAttributeValue (systemElement,
      kAXFocusedApplicationAttribute, (CFTypeRef*) &focused);

// error value results in kAXErrorCannotComplete

```

I have accessibility enabled and have compared my code to code I found on GitHub but nothing seems to work and I'm fresh out of ideas. Perhaps I'm overlooking something?

Answer: 
```swift

import Cocoa
//import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private let systemWideElement = AXUIElementCreateSystemWide()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.leftMouseUp, handler: keyDown)

    }

    func keyDown(event:NSEvent!) {
        let cgevent = CGEvent(source: nil)!.location
        let y = cgevent.y
        let x = cgevent.x
        var ref: AXUIElement?
        let ret = AXUIElementCopyElementAtPosition(self.systemWideElement, Float(x), Float(y), &ref);
        if ret==AXError.cannotComplete{
            print("error")
        }
        print("key down is \(x),\(y),\(ret)");

    }

}

```

I have a similar problem.I also get a cannot complete error. And I have solved it by set com.apple.security.app-sandbox false which is in (your projectname).entitlements.I think this will help you

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>com.apple.security.app-sandbox</key>
        <false/>
        <key>com.apple.security.files.user-selected.read-only</key>
        <true/>
</dict>
</plist>

```
I *tried* to solve this by first setting a messaging timeout:

```
AXError error_code = AXUIElementSetMessagingTimeout( system_element, 0.1f );

```

Which may not have allowed the element to copy the attribute value correctly, but it also didn't cause things to hang (which is what was happening when I was getting the kAXErrorCannotComplete). Once I was done trying to collect the attribute value, I then reset the messaging timeout back to the system default:

```
error_code = AXUIElementSetMessagingTimeout( system_element, 0.0f );

```

It seems this did not actually help in my situation, as I had initially thought. Leaving the answer although it didn't seem to correct the issue, it might provide some information for someone.