0

MacOS: 13.0 (22A380)

swift:

import Cocoa

private func copyToClipBoard() {
    let pasteboard = NSPasteboard.general
    
    var emptyArray = [NSURL]()
    emptyArray.append(NSURL(fileURLWithPath: "/some-file-exist/test"))
    
    pasteboard.clearContents()

    pasteboard.writeObjects(emptyArray)
}
copyToClipBoard()

ObiectiveC:

int main(int argc, const char * argv[]) {
    PasteboardRef clipboard;
    if (PasteboardCreate(kPasteboardClipboard, &clipboard) != noErr) {
        return -1;
    }
    if (PasteboardClear(clipboard) != noErr) {
        return -1;
    }
//    if (PasteboardSynchronize(clipboard) != noErr) {
//        return -1;
//    }
    
    NSURL *url = [NSURL fileURLWithPath:@"/some-file-exist/test"];
    
    PasteboardItemID itemID = (__bridge void *)url;
    
    CFDataRef utf8Data = (__bridge CFDataRef)[[url absoluteString] dataUsingEncoding:NSUTF8StringEncoding];
    PasteboardPutItemFlavor(clipboard, itemID, kUTTypeFileURL, utf8Data, kPasteboardFlavorNoFlags);

    ItemCount itemCount;
    PasteboardGetItemCount(clipboard, &itemCount);
    printf("%ld\n", itemCount);
    
    CFRelease(clipboard);
    CFRelease(utf8Data);
    
    return 0;
}

I try simulate finder copy file action, but so far, I just let item visible in the clipboard, copy action working fine in Finder application, But other application cannot read clipboard file item or use it.

I already search a lot of information, and after comparing, I found that Keyboard Maestro have a function : Set System Clipboard to File Reference, it works just fine.

So, I believe, there must be some way to meet my needs, please help me!

Keyboard Maestro : Set System Clipboard to File Reference

Zheng Xiaodong
  • 143
  • 3
  • 9

1 Answers1

0

Given a file URL to the file (eg [NSURL fileURLWithPath:thePath]), you can write the flavor kUTTypeFileURL with value the UTF8 string encoding of the URL (eg [url.absoluteString dataUsingEncoding:NSUTF8StringEncoding]), for example using PasteboardPutItemFlavor.

As to how you do that with Swift, I have no idea. But that is how Keyboard Maestro writes file references to the clipboard.

Peter N Lewis
  • 17,664
  • 2
  • 43
  • 56
  • Thank you for reply, I updated my methodology for using ObiectiveC, but still only working for Finder. Did I missing something? I was hoping you could point it out for me. – Zheng Xiaodong Nov 01 '22 at 07:25
  • Maybe it's the lack of permission, I found that if file in Desktop or download or else system folder, my code is working, but if I use special folder such as /Users/xxx/tmp/file, will not be allow. But I don't understand why Keyboard Maestro can. – Zheng Xiaodong Nov 02 '22 at 01:17