Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect paste on NSTextField

I'm trying to handle a paste operation on a NSTextField.

I found a similar article but for NSTextView. I tried code similar to this by overriding NSTextField and putting:

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
{
    return [super readSelectionFromPasteboard: pboard];
}

But this method seems to never be called.

Any suggestions on how to detect a past on NSTextField?

like image 745
Kyle Avatar asked Jul 26 '13 12:07

Kyle


2 Answers

You could use the NSTextFieldDelegate delegate method - (BOOL) control:(NSControl*) control textView:(NSTextView*) textView doCommandBySelector:(SEL) commandSelector and watch for the paste: selector.

like image 156
Mark Alldritt Avatar answered Sep 30 '22 14:09

Mark Alldritt


  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.

like image 25
aleclarson Avatar answered Sep 30 '22 16:09

aleclarson