Monitor clipboard in Mac OS
I need to monitor clipboard events in my mac os app. I foun开发者_开发百科d 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?
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...]
Have you looked at this. You could watch for command + c (and x) and manually get the clipboard.
精彩评论