2011-04-30 211 views
3

夥計們!有人知道如何做到這一點?我的意思是:如果我想把一個字符串放到剪貼板上,我會做將文件複製到剪貼板

NSPasteboard *pboard = [NSPasteboard generalPasteboard]; 
[pboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:self]; 
[pboard setString:@"aString" forType:NSPasteboardTypeString]; 

但是如果我想把一個文件放到剪貼板中呢?我想找到一種方法來使用文件路徑作爲參數,然後可以通過上下文菜單或CMD-V將該文件粘貼到Finder中的任意位置。

任何人都可以幫助我嗎?

非常感謝!

回答

5

快速放在一起,但使用CMD + V和上下文粘貼進行測試。

NSURL *object = [[NSURL alloc] initFileURLWithPath:@"/Users/username/Desktop/main.png"]; 
NSPasteboard *pb = [NSPasteboard generalPasteboard]; 
[pb clearContents]; 

NSArray *objectsToCopy = [[NSArray alloc] initWithObjects:object, nil]; 
BOOL pasted = [pb writeObjects:objectsToCopy]; 

if(pasted) // paste was successful 
    NSLog(@"pasted"); 

[object release]; 
[objectsToCopy release]; 
[pb release]; 
0

我還沒有試過,但我瞭解的文件,所有你需要做的(至少在OS X 10.6+)是這樣的:

NSURL *fileURL = [NSURL fileURLWithString:...]; 
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; 
[pasteboard writeObjects:[NSArray arrayWithObject:fileURL]]; 

,並讀取從剪貼板的網址:

NSArray *urls = [pasteboard readObjectsForClasses:[NSArray arrayWithObject[NSURL class]] 
              options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSPasteboardURLReadingFileURLsOnlyKey]]; 
if ([urls count] == 1) { 
    NSURL *myFileURL = [urls objectAtIndex:0]; 
    ... 
} 
+0

...它不工作... :( 還是要謝謝你 – user732274 2011-04-30 10:35:11

5

後幾個小時,和周圍搜索小時,我終於得到了一個簡短的回答...

NSArray *fileList = [NSArray arrayWithObjects:filePath1, filePath2, nil]; 
NSPasteboard *pboard = [NSPasteboard generalPasteboard]; 
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil]; 
[pboard setPropertyList:fileList forType:NSFilenamesPboardType];