3

I need to monitor clipboard events in my mac os app. I found a sample for a clipboard viewer and another question in stackoverflow asking for the same thing, but none of them has a solution on how to monitor the clipboard events.

That is, immediately after the user hits command + c, I get an event notifying. I know that the functionality exists, as there is an app that uses this functionality

Ideas?

Community
  • 1
  • 1
xmorera
  • 1,933
  • 3
  • 20
  • 35
  • 1
    possible duplicate of [Can I receive a callback whenever an NSPasteboard is written to?](http://stackoverflow.com/questions/5033266/can-i-receive-a-callback-whenever-an-nspasteboard-is-written-to) –  Aug 16 '11 at 01:22

2 Answers2

2

I have written a clipboard listener [it will print every new text based information that entered the clipboard] in native Java see the following code:

import java.awt.Toolkit;  
import java.awt.datatransfer.*;  
import java.io.IOException;  

public class ClipboardListener extends Thread implements ClipboardOwner {

    Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  

    public void run(){  
        Transferable selection = systemClipboard.getContents(this);  
        gainOwnership(selection);  
        while (true) {}
    }  

    public void gainOwnership(Transferable t){ 
        try {this.sleep(100);} 
        catch (InterruptedException e) {}
        systemClipboard.setContents(t, this);  
    }  

    public void lostOwnership(Clipboard clipboard, Transferable contents) {
        try {System.out.println((String) clipboard.getData(DataFlavor.stringFlavor));} 
        catch (UnsupportedFlavorException e) {} 
        catch (IOException e) {}
        gainOwnership(contents);  
    }  
}

public class myApp {

    public static void main(String[] args){
        ClipboardListener listener = new ClipboardListener();
        listener.start();}
}

It works, but the application will need focus to get the event from the clipboard. [I'm not Mac OS X developer so I don't how to fix this, actually I have posted a question about it...]

Community
  • 1
  • 1
triple fault
  • 13,410
  • 8
  • 32
  • 45
0

Have you looked at this. You could watch for command + c (and x) and manually get the clipboard.

Matt S.
  • 13,305
  • 15
  • 73
  • 129