How do we get notified about system clipboard even

2019-08-03 17:26发布

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.

标签: java system
1条回答
神经病院院长
2楼-- · 2019-08-03 17:59

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:

  1. Listen to WindowEvents 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.

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

查看更多
登录 后发表回答