Hi all I want to write a simple program (just for learning purposes) that monitors the system clipboard data and serializes its contents.
For example, whenever the user copies some data into the system clipboard (Ctrl-C etc), my program should receive a "notification" and serialize the clipboard data into a file.
I've looked into java.awt.datatransfer but there doesn't seem to be any way I could hook a callback onto the system event whenever data is copied to the clipboard.
How do we get notified about system clipboard events?
It's ok if the solution works only for windows, but OS inter-operability is a plus of course.
Try attaching a FlavorListener
to the Clipboard
by calling Clipboard.addFlavorListener
.
See this SO question which has a code sample and accepted answer: Is it possible to be informed when clipboard content changes outside of java
Update:
That didn't work - as camickr pointed out, that only fires when the DataFlavor
changes. It appears there are two options for you:
Listen to WindowEvent
s and when your app gets focus check the contents of the clipboard. This would be suitable if you don't require your app to do something with the clipboard contents in the background, in other words, the user must switch to your app with something on the clipboard.
Follow this example and poll the clipboard periodically. Obviously you would ignore the Mac-specific stuff (and the poor singleton implementation) but the idea is the same.