macOS中与剪切板相关的接口封装在框架<AppKit.framework>中,主要的类为NSPasteboard,类似iOS系统上的UIPasteboard。
通过接口[NSPasteboard generalPasteboard] 可以获取通用剪切板实例,这个实例为macOS所有App共用,App之间也是通过generalPasteboard来实现内容的复制粘贴。
1. 往剪切板写入内容:
NSString *text = [[NSString alloc] initWithUTF8String:@"demo text"];
// declareTypes接口实际上调用了clearContent接口
if (![[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:nil]) {
NSLog(@"[osxclipboard] Access NSPasteboard failed");
return;
}
if (![[NSPasteboard generalPasteboard] setString:text forType:NSPasteboardTypeString]) {
NSLog(@"[osxclipboard] Set NSPasteboard string failed");
}
2. 清除剪切板内容:
[[NSPasteboard generalPasteboard] clearContents];
3. 监听剪切板内容变化:
NSPasteboard *pasteboard;
int i, changeCount = -1;
while (YES) {
@autoreleasepool {
pasteboard = [NSPasteboard generalPasteboard];
// ignore init state
if (changeCount == -1) {
changeCount = (int)pasteboard.changeCount;
continue;
}
if (changeCount == pasteboard.changeCount) {
continue;
}
changeCount = (int)pasteboard.changeCount;
// 读取改变的内容
NSString *string = [pasteboard stringForType:NSPasteboardTypeString];
if (!string.length) {
continue;
}
NSLog(@"pasteboard: %@", string);
sleep(CLIPBOARD_DETECT_INTERVAL);
}