4

I am writing a program, and within my program at a point I wish to watch the keyboard while my program does not have focus. I use a jar called "JNativeHook" and can be found here http://code.google.com/p/jnativehook/

Onto my issue: This jar works and captures each key press and release event. In my code I keep track of these, on each key press event if a "v" or ctrl key are pressed I set a flag for each, if both are true the user is pasting. When the user initially pastes the program increments a counter to 1. On next paste if the counter is 1 it sets the text of the system clipboard to "Test Paste1" increments the counter, it does this 3 times and on the third it modulus the counter by 3 and restarts. (I plan to add control so that if a certain combination is pressed the keyListener is active and trying to change the system clipboard; pressed again it turns it off)

My problem is that sometimes it does modify the clipboard and I do actually paste the right text and sometimes it does not and I get a error thrown

Exception in thread "pool-1-thread-135" java.lang.IllegalStateException: cannot open system clipboard

So sometimes I can open the keyboard and sometimes not. I am using notepad to do the testing. So I run my program, open notepad, copy something. Then I paste, it says it, then next paste sometimes its right sometimes not, and the next (2nd paste), and the next (3rd). Then if I get all the way through that it starts over.

Why can I not access the clipboard at times, how could I write this so I am guaranteed the text gets to the clipboard?

I figure put the line in a while loop and while there is no exception continue. But I could get into an infinite loop if the clipboard is "in-accessible" for x time.

Continued:

http://stackoverflow.com/questions/14492472/cannot-gain-control-over-clipboard-even-with-controlling-logic

1 Answer 1

0

Some other program has the clipboard open, and the code you are using throws an exception to indicate this.

So, it at first seems like you'd have to busy-wait and give up if you wait for too long. But, there's a possible way around this, by setting your program to be the owner of the clipboard and re-acquiring ownership whenever you lose it (as the owner of the clipboard is notified when it loses ownership).

Read the thread here for a possible solution: http://www.coderanch.com/t/377833/java/java/listen-clipboard

1
  • 1
    I have come to a partial solution. It seems to work better now. I can get more consecutive proper paste take overs. But I still miss a few now and then. @Patashu is there anyway we could discuss the code I now have?
    – user1311286
    Jan 24, 2013 at 1:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.