How to Release system-wide(Global) Hotkeys, Keyboard Shortcut in Java

Here is one way to perform a system-wide (global) keyboard shortcut in out-of-JVM applications.

package com.asjava;

import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class Main {
    public static void main(String[] args) throws Exception {
        Thread.sleep(5000L);

        java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection("Where this come from?");
        clipboard.setContents(tText, null);

        Robot robot = new Robot();

        //Press Hotkey Ctrl+V
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);

        //Typing something
        robot.keyPress(KeyEvent.VK_G);
        robot.keyRelease(KeyEvent.VK_G);

        //Moving mouse to location(0,0)
        robot.mouseMove(0, 0);
    }
}

When starting this program, please switch the focused window to another windows/OS-defined application(for example: notepad) to see what happen.

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code