开发者

Monitor clipboard in Mac OS

开发者 https://www.devze.com 2023-03-28 13:03 出处:网络
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 solu

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消