【Mac】Detecting File Dragging in Cocoa

// properties for preventing consistently calling
var mouseDidDragged = false
var shouldCallForMouseDrag = true
// a system-wide AXUIElement
let systemWideElement = AXUIElementCreateSystemWide()

// MARK: Listen for fileDrag event

NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged) { event in
    if self.shouldCallForMouseDrag {
        self.shouldCallForMouseDrag = false
        self.mouseDidDragged = true

        // getting mouse position
        let (x, y) = NSEvent.mouseLocation.verticalFlippedInScreen().sepratedFloatValue

        // getting accessibility object under the pointer
        var element: AXUIElement?
        guard AXUIElementCopyElementAtPosition(self.systemWideElement, x, y, &element) == .success  else {
            return
        }

        // ask accessibility API for filename attribute
        var value: CFTypeRef?
        guard AXUIElementCopyAttributeValue(element!, kAXFilenameAttribute as CFString, &value) == .success else {
            return
        }

        // check whether there's a filename exist
        guard let _ = value else {
            return
        }

        print("we are dragging a file!")
        // do your thing here
    }
}

NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { event in
    if self.mouseDidDragged {
        self.shouldCallForMouseDrag = true
        self.mouseDidDragged = false

        // undo your thing here
    }
}

// MARK: Helpful NSPoint Extensions

extension NSPoint {
    func verticalFlippedInScreen() -> NSPoint {
        guard let screen = (NSScreen.screens.first { NSPointInRect(self, $0.frame) }) else { return .zero }
        let screenHeight = screen.frame.height
        return NSPoint(x: x, y: screenHeight - y - 1)
    }

    var separatedFloatValue: (Float, Float) {
        return (Float(x), Float(y))
    }
}

Note: This works only when dragging a file in finder. If you want this apply to like when dragging an image inside an application, fell free to add other attribute name to examine, or even combine it with the result of pasteboard’s propertyList.

There you have it, this is how to detecting a file dragging. One thing to remember: If your app is sandboxed, you may found this not working. In this case, you may want to send a email to Apple, tell them what you want to do with this API, and ask them to send you a slightly different .entitlements file.

https://isaacxen.github.io/2018/03/03/detecting-file-dragging-in-cocoa/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值