我正在编写一个程序,该程序侦听系统剪贴板中的更改.剪贴板的内容更改时,侦听器在单独的线程上运行并执行某些操作(例如,写入文件).
我正在使用 ClipboardOwner接口,以便当我的程序失去对剪贴板的所有权(意味着另一个进程已修改剪贴板)时,程序中会触发一个事件,让我可以读取更改.
public class OwnershipClipboardListener extends Thread implements ClipboardOwner { private Clipboard clipB = Toolkit.getDefaultToolkit().getSystemClipboard(); public void run() { /* Initialize ClipboardListener and gain ownership of clipboard */ } @Override public void lostOwnership(Clipboard clipboard, Transferable transferable) { /* Auto-fired when I lose Clipboard ownership. Can do processing and regaining ownership here */ } }问题是,在OSX中运行时,仅当我手动Cmd-Tab到扩展坞中正在运行的进程图标时,剪贴板的任何更改才会反映出来.因此,如果在我切换到停靠图标之前有多个剪贴板操作,则只有最后一个才会起作用.我在Linux或Windows上都不会遇到这个问题.
这就像线程在程序失去焦点时进入睡眠状态,但是最后一个事件触发器在唤醒时仍会触发.有什么办法可以防止我入睡吗?
我怀疑OSX不提供剪贴板更改的通知,因此Java会尽其所能,只要它因其他原因被唤醒就通知您.我的怀疑来自 NSPasteboard 文档,尤其是changeCount例程.它说:因此,您可以在拥有粘贴板所有权时记录更改计数,然后将其与changeCount返回的值进行比较,以确定您是否仍然拥有所有权."没有提及使用事件来检测更改.
I'm writing a program that listens to the System Clipboard for changes. The listener runs on a separate thread and performs some action (say, write to file) when the contents of the Clipboard changes.
I'm polling the clipboard using the ClipboardOwner interface, so that when my program loses ownership of the Clipboard (meaning another process has modified the clipboard) an event is fired in my program letting me read the changes.
public class OwnershipClipboardListener extends Thread implements ClipboardOwner { private Clipboard clipB = Toolkit.getDefaultToolkit().getSystemClipboard(); public void run() { /* Initialize ClipboardListener and gain ownership of clipboard */ } @Override public void lostOwnership(Clipboard clipboard, Transferable transferable) { /* Auto-fired when I lose Clipboard ownership. Can do processing and regaining ownership here */ } }The problem is, when running in OSX, any change to the clipboard is reflected only if I manually Cmd-Tab to the running process icon in the dock. So if there multiple clipboard operations before I switch to the dock icon, only the last one has any effect. I don't face this issue on Linux or Windows.
It's like the thread goes to sleep when the program loses focus, but the last Event trigger still fires when it wakes up. Is there any way I can prevent this sleep?
解决方案I suspect that OSX doesn't provide notification of clipboard changes, so Java is doing the best it can by notifying you whenever it gets woken for some other reason.
My suspicion comes from the NSPasteboard docs, the changeCount routine in particular. It says "You can therefore record the change count at the time that you take ownership of the pasteboard and later compare it with the value returned from changeCount to determine whether you still have ownership." No mention of using an event to detect changes.
更多推荐
Java线程在不关注OSX时进入睡眠状态
发布评论