PDA

View Full Version : Pasteboard notification




mathcolo
Apr 4, 2009, 10:02 PM
For a Cocoa program that I'm developing, I'd like to have my program watch the pasteboard for new pastes and add a 1 to it. For example, the program would automatically do this:

I Paste Hello
The program makes it 1Hello

I've been looking at NSNotification and the shared notification center but I didn't find a notification for doing this. Any assistance would be greatly appreciated. Thanks!



kainjow
Apr 4, 2009, 10:35 PM
AFAIK, you have to poll the pasteboard for changes. I don't think there's any sort of event/notification sent when it changes.

mathcolo
Apr 5, 2009, 09:15 AM
AFAIK, you have to poll the pasteboard for changes. I don't think there's any sort of event/notification sent when it changes.

Wouldn't that use a lot of CPU?

kainjow
Apr 5, 2009, 10:12 AM
Nope, with this little test it only uses 0.02% running every 1/4th of a second:

#import <Cocoa/Cocoa.h>


@interface Watcher : NSObject {
NSInteger lastChangeCount;
NSPasteboard *pasteboard;
}
@end

@implementation Watcher
- (id)init {
if (self = [super init]) {
pasteboard = [[NSPasteboard generalPasteboard] retain];
[NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(checkPasteboard:) userInfo:nil repeats:YES];
}
return self;
}

- (void)checkPasteboard:(NSTimer *)timer {
NSInteger currentChangeCount = [pasteboard changeCount];
if (currentChangeCount == lastChangeCount)
return;
NSLog(@"Pasteboard changed: %@", [pasteboard types]);
lastChangeCount = currentChangeCount;
}
@end


int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[Watcher alloc] init];
[[NSRunLoop currentRunLoop] run];
[pool release];
return 0;
}