Clipboard monitoring on Mac OS X | Java

2020-02-28 04:59发布

问题:

I'm having troubles getting data from the system clipboard on Mac OS X. What I'm trying to do is to listen to the system clipboard and print the content of the clipboard each time new [text based] information is put into it.

The problem: bellow code works perfectly fine on Windows 7 and openSUSE Linux machines, however when I try running the same code on Mac OS X the program fails to print the new content of the clipboard until focus is given to the application. [Nothing is printed until I click on the application icon on the dock...]

My source 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);  
    }  

    public void gainOwnership(Transferable t){ 
        try {this.sleep(100);} 
        catch (InterruptedException e) {e.printStackTrace();}
        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();
        while(true){}}

}

What I'm missing/doing wrong?

[Update] I found similar problem posted here: Java thread goes to sleep when not in focus on OSX However using the command "java -jar myApp.jar &" didn't work as a workaround for me.

回答1:

This seems to be an open bug, see MACOSX_PORT-511 ClipboardOwner method lostClipboard is not called if app is not focused.



回答2:

It seems that there is no elegant way around this problem, NSPasteboard does not provide clipboard ownership concept. You can't even solve this problem writing native Objective C.

The only solution is to periodically sample the clipboard.