Register for global file drag and drop events in Cocoa

I am trying to get a notification when an OS X user drags any file in OS X, and not just into my application.

My current approach used addGlobalMonitorForEventsMatchingMask:handler: on NSEvent , as shown below:

 [NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDraggedMask handler:^(NSEvent* event) { NSPasteboard* pb = [NSPasteboard pasteboardWithName:NSDragPboard]; NSLog(@"%@", [pb propertyListForType:NSFilenamesPboardType]); }]; 

This works in part - the handler is called when I start dragging a file from my desktop or Finder, however it also gets called when I perform every other operation that contains left-clicking, for example. moving the window. The problem is that NSDragPboard still contains the last dragged file URL, for example. when I turn off the file and start moving the window, which makes it difficult to distinguish between these operations.

TL DR - I'm interested in dragging and dropping files in a system-wide area. I don’t need any information about the dragged file, just the information that the dragging and dropping file was started or stopped. I would be grateful for a possible solution to this issue.

+5
source share
2 answers

After talking with the Apple DTS, this is most likely a mistake. I registered rdar: // 25892115 for this problem. Currently, there seems to be no way to solve my original question with this API.

To solve my problem, I now use the Accessibility API to find out if the item under the cursor is a file (kAXFilenameAttribute is not NULL).

+2
source
 NSPasteboard* pb = [NSPasteboard pasteboardWithName:NSDragPboard]; NSArray* filenames = [pb propertyListForType:NSFilenamesPboardType]; NSInteger changeCount = pb.changeCount; //when moving a window. the changeCount is not changed, use it to distinguish if (filenames.count > 0 && self.lastChangeCount != changeCount){ self.lastChangeCount = changeCount; //your code here } 
0
source

Source: https://habr.com/ru/post/1247375/


All Articles