I want to find a way to do kind of a custom "paste from clipboard" action. Let's assume the content of clipboard is text for simplicity (not a file). Whenever you press Ctrl+V
, it inserts that content (which is text) to a current open file which has a focus.
I have an app for catching a global hotkey. Note this is not a window application, it's a console one and it catches the hotkey globally. Let's say I have the hotkey of Ctrl+U
. So what I want to do is when I press Ctrl+U
I want to insert some predefined text to a current open file. Just like Ctrl+V
does! The differences from a standard Ctrl+V
is that I want to insert a predefined text and the hotkey is different.
How do I do this?
I'd prefer a cross-platform solution, however first of all I'm going to do that for Linux, specifically Ubuntu. The language is not important but Java or Scala would be better. Of course, I understand that the solutions is Java uses native OS' API for that.
I'm hoping that this hackish solution would work, but it is still untested, I am unsure how to catch the event for the hotkey.
The idea behind this code is the following five steps:
This should give the appearance of a new clipboard (if not, hopefully it inspires you to come up with a better, less hackish solution).
Without further ado, here is my code. First I have a simple helper method to set the value of the clipboard (as we do this twice).
And then, I have a main method where I go through the five steps in order.
[Edit]:
Here is some code to test what kind of contents are in the Clipboard - image, text, etc. The unicode error was coming from the fact that the old contents of the clipboard were something that couldn't be represented by a plain String. To fix this error, you will have to check if the old contents were an image, the old contents were text, and save them accordingly.
If the contents are text, then for saving and writing the content you would use the old method, repasted below for convenience.
However, if the contents are an image, then for saving temporarily and rewriting you need to do the following. Note that the code for writing the image is not mine, but is taken from the accepted answer at Setting images to Clipboard - Java
Taken from Setting images to Clipboard - Java :