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.


  1. Override the becomeFirstResponder method of your NSTextField

  2. Use object_setClass to override the class of the "field editor" (which is the NSTextView that handles text input for all NSTextField 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
  1. Create your MyFieldEditor class and override its paste: 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.