views:

370

answers:

3

I want to make simple java program that will insert some text into current cursor position. That cursor position can be in any text editor, for example notepad. Is this possible?

+1  A: 

Using this article as a base about copy/paste, you may see that you can only put something to the clipboard but not directly changing the content of a foreign's process Textbox.

You might want to get the window handle of the box and send a message to it using the Windows API. This works on windows only, I don't know whether there's an equivalent way on Mac OS / Linux. Maybe this doesn't even work directly from java. You would need to type some C/C++-code and use the Java Native Interface (JNI)

regards

Atmocreations
thanks. I'll try with JNI
dede
A: 

If u are asking for the current cursor location, i think u should use this :

Display.getCurrent().getCursorLocation()

Having the cursor location, what to do next requires further details. If u want to automatically write some text into foreign applications like Word or Notepad, this sounds more like a virus to me..

Hypercube
Yes, I want to write into any text editor (like Notepad) and I'm making something like clipboard utility (similar to http://www.deepskyblue.net/software/sanvient/en/). I cannot figure out how this program can write to any text input.
dede
+1  A: 

It's a hack, but look into java.awt.Robot. It lets you programmatically make mouse clicks and key presses, among lots of other useful things. So one way to do it would be:

  1. Use Atmocreations' article to put text in the clipboard
  2. When you want to paste it, use Robot to click at the current position (if you need to give that field focus)
  3. Use Robot to press Ctrl-V (or whatever your system expects for a paste)

Like I said, it's not at all a clean solution, but it will work in a pinch.

perimosocordiae
I'm using:robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL);robot.keyPress(KeyEvent.VK_V);robot.keyRelease(KeyEvent.VK_V);robot.keyRelease(KeyEvent.VK_CONTROL);and it works. Thanks. P.S. I tried with robot.keyRelease(KeyEvent.VK_PASTE); but it throws an error
dede
@peri: does that work even if the focus is on a different window?
Atmocreations
no, it' works just for window in focus
dede
Right. It has the exact same effect as actually pressing Ctrl-V on the keyboard, so it'll paste wherever the focus is.
perimosocordiae