Monitor clipboard in Mac OS

冷暖自知 提交于 2019-12-10 10:19:51

问题


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?


回答1:


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...]




回答2:


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



来源:https://stackoverflow.com/questions/7072533/monitor-clipboard-in-mac-os

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