Can I receive a callback whenever an NSPasteboard is written to?

后端 未结 6 1903
迷失自我
迷失自我 2020-12-02 09:26

I\'ve read Apple\'s Pasteboard Programming Guide, but it doesn\'t answer a particular question I have.

I\'m trying to write a Cocoa application (for OS X, not iOS) t

6条回答
  •  孤城傲影
    2020-12-02 09:43

    For those who need some very simplified version in Swift 5, it just works(base on @Devarshi code):

        func WatchPasteboard(copied: @escaping (_ copiedString:String) -> Void) {
            let pasteboard = NSPasteboard.general
            var changeCount = NSPasteboard.general.changeCount
            Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
                if let copiedString = pasteboard.string(forType: .string) {
                    if pasteboard.changeCount != changeCount {        
                        copied(copiedString)                
                        changeCount = pasteboard.changeCount
                    }
                }
            }
        }
    

    Usage of how to use is as below:

    WatchPasteboard {
        print("copy detected : \($0)")
    }
    

    it will print out like below..

    watched : pasteboard1
    watched : pasteboard2
    

提交回复
热议问题