Monitor clipboard in Mac OS

自闭症网瘾萝莉.ら 提交于 2019-12-06 02:15:42
Naftaly

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!