Detecting a key pressed anywhere

How do you detect a key that is pressed no matter what window is selected?

System.in.read()Because Windows only has Canonical mode for its DOS input,
this always blocks which may not be what you want.
see the example I posted earlier.
http://forum.java.sun.com/thread.jspa?threadID=664543&messageID=3892105#3892105
(T)

Similar Messages

  • How to detect any key pressed for program running in the background?

    Hi All,
    is it possible to detect when any key is pressed if a java program is not in the focus? For example, when I have a console based program I can write something like:
    System.in.read();
    and wait until any key is pressed. However, if I move the mouse away from the console and make any other window active, the console program "doesn't hear" anything. Ok, it's clear, of course, but how is it possible to make the program detect any keys pressed even if it's running in the background?
    Thanks a lot for any hints!

    qnx wrote:
    1) Stop trying to make spyware. -> I don't do anything like this!
    2) Stop re-posting the same questions. -> didn't know they are the same, sorry.
    3) Stop taking us for fools. -> what? Honestly, I don't think that I realy deserved this :)With a limited posting history and the type of questions you are asking they are unusual.
    There are very few legitimate problem domains that would require what you are asking about. There are illegitimate ones though. And the legitimate ones would generally require someone with quite a bit of programming experience and would also be required (the fact that java can't do it would not get rid of the requirement.)
    Thus one might make assumptions about your intentions.

  • I want to detect a key press

    To detect a key press, i know i have to use the keylistener class
    public class key implements KeyListener{
         public static void main (String args[]){
              addKeyListener(this);
              keyReleased(KeyEvent e) {}
              keyTyped(KeyEvent e) {}
              keyPressed(KeyEvent e) {
    I built a simple program but it doesn't compile, it has an error.
    All i want is to detect a key press and do something for key presses...
    What am i doing wrong?

    I once got the following demo file somewhere in the Sun/Java site, probably in one of the link cited above..
    * Swing version
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    public class KeyEventDemo extends JApplet
                              implements KeyListener,
                                         ActionListener {
        JTextArea displayArea;
        JTextField typingArea;
        static final String newline = System.getProperty("line.separator");
        public void init() {
            JButton button = new JButton("Clear");
            button.addActionListener(this);
            typingArea = new JTextField(20);
            typingArea.addKeyListener(this);
            displayArea = new JTextArea();
            displayArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(displayArea);
            scrollPane.setPreferredSize(new Dimension(375, 125));
            JPanel contentPane = new JPanel();
            contentPane.setLayout(new BorderLayout());
            contentPane.add(typingArea, BorderLayout.NORTH);
            contentPane.add(scrollPane, BorderLayout.CENTER);
            contentPane.add(button, BorderLayout.SOUTH);
            setContentPane(contentPane);
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            displayInfo(e, "KEY PRESSED: ");
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
        /** Handle the button click. */
        public void actionPerformed(ActionEvent e) {
            //Clear the text components.
            displayArea.setText("");
            typingArea.setText("");
            //Return the focus to the typing area.
            typingArea.requestFocus();
         * We have to jump through some hoops to avoid
         * trying to print non-printing characters
         * such as Shift.  (Not only do they not print,
         * but if you put them in a String, the characters
         * afterward won't show up in the text area.)
        protected void displayInfo(KeyEvent e, String s){
            String charString, keyCodeString, modString, tmpString;
            char c = e.getKeyChar();
            int keyCode = e.getKeyCode();
            int modifiers = e.getModifiers();
            if (Character.isISOControl(c)) {
                charString = "key character = "
                           + "(an unprintable control character)";
            } else {
                charString = "key character = '"
                           + c + "'";
            keyCodeString = "key code = " + keyCode
                            + " ("
                            + KeyEvent.getKeyText(keyCode)
                            + ")";
            modString = "modifiers = " + modifiers;
            tmpString = KeyEvent.getKeyModifiersText(modifiers);
            if (tmpString.length() > 0) {
                modString += " (" + tmpString + ")";
            } else {
                modString += " (no modifiers)";
            displayArea.append(s + newline
                               + "    " + charString + newline
                               + "    " + keyCodeString + newline
                               + "    " + modString + newline);
    }

  • Detecting two keys press at one time

    i need to do a event handler, say when user press shift + enter, it will do something, else enter would do another thing
    i tried but i can't get the event handler to detect two key press, how do I go about it?

    VK_ENTER vs (VK_ENTER + SHIFT_DOWN_MASK)

  • Detecting asyncronous key press

    Hi all, I'm trying to figure out whether there is any way to detect an asynchronous key press for a simple and line-oriented java task.
    I mean no GUI, AWT and alike.
    All examples I could see refer to AWT events.
    The goal is to break long and time consuming processes upon pressing (for example) ctrl-c like we used to to in C++.
    Thanks.

    Word is not a JVM mastered process.
    I'm referring to what it seems the standard behavior of the JVM. I can be notified about ctrl-c, but I cannot change its standard action of terminating the JVM process.
    I tried by catching SIGINT using sun.misc.* - it works fine, handler is called - however upon returning (even without calling the previous handler - if any) the process exits.
    I don't see any way to change this - which was my primary goal.

  • Using InputMap and ActionMap to detect any key pressed...plz help

    Hi,
    I am quite new to Java. I have a tiny problem. I wanna put an actionlistener into a JTextField, so it printout something whenever a key is pressed (when the textField is selected).
    I can only get it to print if I assign a specific key to pressed...example below (works):
    JTextField searchBox = new JTextField();
    InputMap imap = searchBox.getInputMap();
    ActionMap amap = searchBox.getActionMap();
    imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "pressed");
    amap.put("pressed", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
                   System.out.println("TYPEEEEEEEEEEEEEEE");
    HOWEVER, when i change keystroke to any key pressed, it doesn't work. Example below(doesn't work):
    JTextField searchBox = new JTextField();
    InputMap imap = searchBox.getInputMap();
    ActionMap amap = searchBox.getActionMap();
    imap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "pressed");
    amap.put("pressed", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
                   System.out.println("TYPEEEEEEEEEEEEEEE");
    Somebody plz helps me. I am really confused how to use KeyEvent.KEY_PRESSED. I thought it would work the same way as KeyEvent.VK_A...if i can't use KEY_PRESSED for that purpose, what KeyEvent do I use?
    Thank you very much in advance.

    Sounds like you want a KeyListener.
    textField.addKeyListener(new KeyListener() {
        public void keyTyped(KeyEvent e) {
            System.out.println("Key typed.");
        public void keyPressed(KeyEvent e) {
            System.out.println("Key pressed.");
        public void keyReleased(KeyEvent e) {
            System.out.println("Key released.");
    });See the API documentation for more information.

  • How to detect space key pressed event

    I am working on a japplet where it is needed to pause the applet on the occurrence of a space bar key pressed event can anybody help
    thanks in advance

    Have a look at the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    -Puce

  • Detecting a Key Press

    I am using this code to set up a listener for a key press. I
    noticed that it works fine when you use a LEFT, RIGHT etc. press,
    but it will not work with a regular key press(i.e. ctrl+P). It says
    that there is an undefined property as far as the Letter goes. If
    anyone can help me with this, I would very much appreciate it.
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
    function keyDown(event:KeyboardEvent):void
    if(event.ctrlKey)
    var key = event.keyCode;
    var P_key = Keyboard.P;
    switch(key)
    case P_key:
    trace("this thing works");
    break;
    }

    Ok, I've figured it out. Flash decided to take me for a fool
    and pretended like it would take the P-key as a press, but in
    actuality, it only works that way in AIR.

  • Detecting multiple key presses

    Using the code below I am trying to detect keypresses for a java applet which involves holding down of several keys at once. I have 2 problems, probably related. Firstly I can only detect 3-4 simultaneous keys being held down and secondly the keyPressed and released! events are continually fired while a key is held down not just when it was first pressed as you would think. I would like to be able to detect up to a maximum of 16 keys being held down at once, is this possible? I am working on a unix system in x-windows which I think accounts for the auto-repeat problem, but why am I having trouble detecting multiple simultaneous keys being held down?
    It there a boolean function I can call to check the state of given keys at a given time, that would be very useful?
    Any help is appreciated.
    Ian
    public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=true;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=true;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
         qdown=true;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=true;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=true;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=true;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=true;
    break;
    }//method keypressed
    public void keyTyped(KeyEvent e) {
    }//method keytyped
    public void keyReleased(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=false;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=false;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
    qdown=false;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=false;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=false;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=false;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=false;
    break;
    }//method keyReleased

    Did you ever find a solution to this problem. I am experiencing a similar problem. I want to be able to disable the auto-repeat function of the keyboard, so that I can tell if the user is holding down the key, or pressing it several times.
    If you have found a solution please let me know at [email protected]
    Thanks,
    Ben Newton

  • Key press detection when application is running in the background

    Is it possible to detect any key presses when the application is in the background?

    The key-related, pointer-related, and paint() methods will only be called while the Canvas is actually visible on the output device. These methods will therefore only be called on this Canvas object only after a call to showNotify() and before a call to hideNotify(). After hideNotify() has been called, none of the key, pointer, and paint methods will be called until after a subsequent call to showNotify() has returned. A call to a run() method resulting from callSerially() may occur irrespective of calls to showNotify() and hideNotify().
    The showNotify() method is called prior to the Canvas actually being made visible on the display, and the hideNotify() method is called after the Canvas has been removed from the display. The visibility state of a Canvas (or any other Displayable object) may be queried through the use of the Displayable.isShown() method. The change in visibility state of a Canvas may be caused by the application management software moving MIDlets between foreground and background states, or by the system obscuring the Canvas with system screens. Thus, the calls to showNotify() and hideNotify() are not under the control of the MIDlet and may occur fairly frequently. Application developers are encouraged to perform expensive setup and teardown tasks outside the showNotify() and hideNotify() methods in order to make them as lightweight as possible.
    The above answer you might have found in the JAVADOC, if you would have gone through the description of the Canvas class.
    Don't forget your DUKES as I had to search the JAVADOC for giving you the exact answer, which you should have done that yourself only!!!
    Shan!!!

  • Detecting Key Press at App Startup

    I would like to detect a press of the Shift key (ideally) when my application starts.
    If the user is pressing the key, display a normally hidden dialog allowing the user to select the language to use. If the key is not pressed, continue starting the application in the default language.
    From the Java Tutorial, it seems I can only detect a key press if the focus in on a GUI element is already visible. This defeats the purpose of having the special dialog be hidden.
    Any suggestions?

    From the Java Tutorial, it seems I can only detect a
    key press if the focus in on a GUI element is already
    visible. This defeats the purpose of having the
    special dialog be hidden.I believe this is because you are 'listening' for a key press from your GUI class
    Any suggestions?Sounds like you need to Listen for a key press in your running code
    you could try to give the GUI focus while still having it hidden(don't know if that would work)AND Make sure that you have your GUI and main APP in seperate threads. This would, of course, require a pause in your main app to change the language, so if you can get a key listener in your main app i think that would solve all probs.
    sorry if this sounds confusing

  • Backlight key presses not detected, OPTIMUS, wiki didn't help

    I am using a Razer Blade 14" with linux-ck kernel (although I have tested in the main kernel and the issue remains).
    The keyboard brightness settings keys are not detected by X at all (using xev reports no keycodes when I press them).
    However, the driver is getting that information. And in the same type as other function keys (such as sound up/down - which are detected correctly).
    I know this because, while investigating the workings of the touchpad, I ran the razer-test script found in:
    http://fxchip.net/RazerBlade/
    (slightly modified because the device ID is 0x011D in the 14").
    It distinguishes normal key presses from Macro Keys. Function keys in this laptop are macro keys. When pressing volume down, I get the following report:
    Macro keys: Razer Extra Buttons:
      Extra key: FN
    04 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    Macro keys: 02 ea 00 00
    Macro keys: 02 00 00 00
    Macro keys: Razer Extra Buttons:
    04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    When pressing brightness up/down, I get the following report:
    04 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    Macro keys: 02 70 00 00
    Macro keys: 02 00 00 00
    Macro keys: 02 6f 00 00
    Macro keys: 02 00 00 00
    Macro keys: Razer Extra Buttons:
    04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    (note that the last part just signals that I let go of the FN key)
    My idea was to try to find the keycodes through xev and then map them manually. However, this was unsuccessful since xev reports no input when I press brightness up/down (while volume up/down works).
    This is where I'm lost - the keyboard drivers seems to just be ignoring them.
    Any help appreciated . Let me know what I can post if it's of any help!
    Cheers,
    Rodrigo
    EDIT:
    My laptop uses optimus hardware, and I'm using the integrated Intel Graphics card.
    I have tried all the methods in the wiki but none of them worked:
    https://wiki.archlinux.org/index.php/backlight#Overview
    https://wiki.archlinux.org/index.php/In … ter_resume.
    It's also worth noting that I do have control over the backlight with software - the FN+F8/F9 key bindings are the ones that are just completely ignored by the driver.
    Last edited by rgomes (2013-11-22 18:47:57)

    maxo wrote:
    Hey. If you aren't using the nvidia graphics card then this works on mine.
    Edit the /etc/X11/xorg.conf.d/20-intel.conf by adding
    Option "Backlight" "intel_backlight"
    Xorg normally automatically selects the backlight device. On mine it ued acpi_video0 instead of intel_backlight.
    Hope that helps!
    Thanks, but the challenge is, to get nvidia prop. drivers working.
    I think, I tracked the problem down to some backlight issue, probably a firmware issue with the laptop model.
    On ubunutu, ideapad backlight modules gets loaded, on arch, it uses the intel-bl. As it stands to reason, backlight settings are too dim when starting X.
    I am about to test nvidia-bl from AUR.

  • Detect Key Press and Mouse Motion in ONE event?

    Hi
    I am trying to create a functionality where a mouse motion from left to right performs one action, and the same motion while a given key is pressed performs another action.
    How can i combine the two events? How do I unify the KeyEvent and MouseEvent, particulary when I need to capture the directional motion of the mouse together with the key press?
    many thanks for any insight

    you cannot actualy combine them into 1 event but there is an easy way around this:boolean mouseKeyPressed = false;
    public void keyPressed (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or e.isCtrlDown(), e.isAltDown(), ...
        mouseKeyPressed = true;
    public void keyReleased (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or !e.isCtrlDown(), !e.isAltDown(), ...
        mouseKeyPressed = false;
    public void mouseMoved (MouseEvent e)
      if (mouseKeyPressed)
        //processAction
    }hope this helps,
    greetz,
    Stijn

  • Detecting key press on Windows

    Hi! I want to do a program that can catch every key press in Windows, no matter in wich application the user is (nope... I'm not developing a virus for those of you who are thinking that)... does any one knows how to do this?
    Thanks!

    The technique is called "keyboard hooking" and you can search for the Windows API "SetHookWindowsEx". C and Windows API knowledge is mandatory.

  • Catching Alt Key Press with the Key Down Filter Event

    I am writing an application that requires specific key combinations using ctrl, shift, and alt in addition to a function key (F1, F2, F3, etc).  The application works great except for when I try to catch an alt key press.  The alt key press does not seem to fire an event eventhough it is an option in the PlatMods cluster as well as the VKey enum.  When I press the alt key when my application is running the cursor changes to a normal mouse pointer from the usual finger pointer and prevents any other key presses from going through (in addition to not firing an event itself).
    I have tried completely removing the run-time menu, which doesn't seem to help.  I currently discard all keys after I handle them in my event structure.
    I really hope that the only solution isn't using a Windows DLL.  Any suggestions or ideas at all would be greatly appreciated.
    Thanks,
    Ames

     Hi Ames
    As Kileen has said Khalid has already given you a good solution to detect the ALT key.
    I have another approach that might let you stick to your event-driven approach. I suggest that you have another loop in your app that polls the keyboard using the Input Device utility vi's. When this poll loop sees an ALT + KEY combo it raises a dynamic user event and will be processed in your event structure. This means you can keep your key down filter event to process the CTRL + KEY and SHIFT + KEY events.
    Example attached in 7.1
    cheers
    David
    Attachments:
    Catching Alt Key Press Poll with Events(151551).vi ‏89 KB

Maybe you are looking for