Detect paste on NSTextField
You could use the NSTextFieldDelegate
delegate method - (BOOL) control:(NSControl*) control textView:(NSTextView*) textView doCommandBySelector:(SEL) commandSelector
and watch for the paste:
selector.
Override the
becomeFirstResponder
method of yourNSTextField
Use
object_setClass
to override the class of the "field editor" (which is theNSTextView
that handles text input for allNSTextField
instances; see here)
#import <AppKit/AppKit.h>
#import <objc/runtime.h>
@interface MyTextField : NSTextField
@end
@implementation MyTextField
- (BOOL)becomeFirstResponder
{
if ([super becomeFirstResponder]) {
object_setClass(self.currentEditor, MyFieldEditor.class);
return YES;
}
return NO;
}
@end
- Create your
MyFieldEditor
class and override itspaste:
method
@interface MyFieldEditor : NSTextView
@end
@implementation MyFieldEditor
- (void)paste:(id)sender
{
// Get the pasted text.
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSString *text = [pasteboard stringForType:NSPasteboardTypeString];
NSLog(@"Pasted: %@", text);
// Set the pasted text. (optional)
[pasteboard clearContents];
[pasteboard setString:@"Hello world" forType:NSPasteboardTypeString];
// Perform the paste action. (optional)
[super paste:sender];
}
@end
All done! Now you can intercept every paste action.