Capturing system-wide key events

I am writing a pseudo-wordprocessor, and have a StatusBar class that is (supposed) to show the user their status... e.g. whether Insert or Caps Lock are enabled. To do that, I obviously need to check whether those keys are pressed.
However, I don't know exactly how to perform such a check. I assume it has something to do with a system-wide KeyListener, but how would I implement that?

see this code
I hope i've understand you!!!
bye,
leo
import java.awt.event.*;
import javax.swing.*;
public class CaputreKey extends JFrame {
JLabel txt = new JLabel();
public CaputreKey() {
txt.setBounds(10, 20, 100, 100);
this.setBounds(10, 10, 300, 300);
this.getContentPane().setLayout(null);
this.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e) {
all_keyPressed(e);
this.getContentPane().add(txt, null);
public void all_keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_CAPS_LOCK)
txt.setText("CAPS");
else if (e.getKeyCode() == e.VK_INSERT)
txt.setText("INSERT");
else
txt.setText("OTHER");
public static void main(String[] args) {
CaputreKey caputreKey1 = new CaputreKey();
caputreKey1.show();
}

Similar Messages

  • Capture system-wide keypresses in c/c++, what library to use?

    I want to be able to capture system-wide keypresses with a JAVA application in OSX. As this is not possible using pure java, I need to write a C/C++ app that does the listening, and combine that with my java app using JNI.
    But that is not my problem
    I was looking at this great tutorial:
    http://ubuntuforums.org/showthread.php?t=864566
    It does what I want, but for linux, and uses the X11 library's for the actual keypressdetection.
    As I don't know much about C/C++ for OSX specificly, my question is, what would be a good library for replacing X11 with (preferably something that everyone already has, like X11 in linux). I know I could use SDL or something for this, but isn't there anything a little closer to the system that everybody has by default?
    Thanks
    Reinout

    It would be best if you post this question on the Real Time forums since you are working with RT.
    Applications Engineer
    National Instruments

  • Capturing the TAB key event.

    How can I capture the TAB key event?
    I am trying to use it within a JTextField to do a normal text tab operation.
    Thanks,
    D

    I want to map the Tab key to a jTextField so that when the user is editing inside the jTextField they can press the TAB key to tab over a predefined number of characters.
    Thanks,
    D

  • Mapping code to a system wide event (keypress)

    I wanted to know if it was possible to have a java program run a procedure based on a system wide keyboard event (say a funtion key was pressed). For instance if someone were in a word processor they would hit the "F1" key on their keyboard and that would cause something to happen on the Java app running in the background, say past some text or something from the java app into the word processor through clipboard.
    Thanks in advance.

    to the best of my knowledge the only way to do this is to have a native application that can then invoke the java program. You will need to look into JNI (Java Native Interface).

  • Capturing Enter key event from text box

    In my application, there are a number of text boxes. I want to create a feature where an enter key even is seen and specific function executed depending on which text box was in focus when the enter key was pressed. Currently I am able to capture an enter key event on the whole page. How do I do that specifically for a text box?
    This application is done in HTML, javascript and Adobe AIR.
    Thanks
    Binu
    www.verseview.info

    Hi
    That's true that Flex4.5 SDK under Flash builder Burito doesn't listen Enter key in Text Area for KeyUp or KeyDown event.
    Here I found a work around you can use.
    Add an eventlistener to the component in actionscript and set the useCapture=true next to eventlistener function. Now you can listen enter key for KeyUp or KeyDown Event
    Hope this helps
    Rush-me

  • Capture desktop key event to control my screen capture app

    I want to write a screen capture program to capture screen when I am playing fullscreen game or other desktop window application. But the java screen capture program can only receive key or mouse event when it is focused. So how do I capture key event when I am focusing other app or fullscreen app?
    Do I have to use JNI and call some OS specific API. My target OS is WinXP. Help or suggestions are appreciated!!

    Hi All,
    I was wondering if there is a way to capture the top-most
    window or dialog box. This is something that will
    generally be running outside of the JVM....We,
    as programmers, need a Rectangle instance that describes the area
    of interest to be captured (i.e., location and size).
    Thus, a routine that interfaces to the Native windowing system (Toolkit?)
    might look something like:
    Rectangle rect = tk.getRectangleForTopMostComponent();
    Does anything like this exist?
    Thanks!
    - DocJava

  • KeyListener does not capture Arrow key Events in textField

    Love................
    I added a key listener to TextField it does not detect
    Arrow Keys events in keyTyped, KeyPressed,KeyReleased methods
    why?????
    I want to shift focus from a textfield to other component
    on capturing Arrow key Pressed How

    Here is a Java demo where it works since it is not a printable character you must get the keyCode:
    http://java.sun.com/docs/books/tutorial/uiswing/events/example-swing/index.html#KeyEventDemo
    public class KeyEventDemo ... implements KeyListener ... {
    ...//where initialization occurs:
         typingArea = new JTextField(20);
         typingArea.addKeyListener(this);
    /** 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: ");
    protected void displayInfo(KeyEvent e, String s){
         char c = e.getKeyChar();
         int keyCode = e.getKeyCode();
         int modifiers = e.getModifiers();
         tmpString = KeyEvent.getKeyModifiersText(modifiers);
         ...//display information about the KeyEvent...
    }

  • Can't capture key event in applet

    Hi,
    Currently i'm developing an applet. However, i fail to capture the key event in the applet. The key that i fail to capture is VK_TAB. Any idea to handle this?
    Thanks in advance!

    to capture key event, u need to
    1. addKeyListener
    2. focus on that component (yourApplet must focusable)

  • How to capture backspave and delete key events

    Hi ,
    i would like perform some javascript code on pressing backspace or delete key.
    initially i thought of adf clientlsitener keypress event.but this is not capturing backsapce key event
    what is the alternate way capture backspace or delete key event?
    please help

    Hi
    the following script cancels the input event when the back key is pressed
           function keyTrap(inputEvent){
             var keycode = inputEvent.getKeyCode();
             if(keycode ==8){
               inputEvent.cancel();
           }Use a clientListener
            <af:inputText label="Label 4" id="it7">
              <af:clientListener method="keyTrap" type="keyDown"/>
            </af:inputText>Frank

  • Capture 'Enter' key event

    Hi,
    Is there any way we can capture the event when a user presses the enter key inside a text field?

    Hi andrewquay
    you can capture the enter key by adding the following code in the textfield's change event.
    if(xfa.event.change == "\u000a")
    xfa.host.messageBox("enter key is pressed");
    mail: [email protected]

  • Capture Key events

    I am trying to create a program to capture key events, regardless of where the focus is. For example, any time the user presses ctrl-t, I would like to call a particular method, if the user is in Microsoft Word, Internet Explorer, Halo, or any other application. However, a glass pane would not work, because all other key events will be needed by the current application. This would be identical to Microsoft' s ctrl-alt-del and Microsoft's alt-tab. Any ideas would be greatly appriciated. Post here or E-mail be at [email protected]

    This is not true, think of all the keylogger programs out there that allow you to do this.
    It's not a security issue.
    I also am wondering how to capture a key on a java application without it having focus. An example is a timer in a game. I should be able to be in a full screen game and hit F1 or Home or whatever I choose and have a timer start that will ding at me in 1 minute to let me know that my time is up.
    It is in a way similar to CTRL ALT DEL in that you don't ahve to be focused on anything in particular to use it but that isn't really the best analogy.
    If anyone can point me in the right direction to figure out how I would go about this, please tell me. Or if it is not possible for a program written in java to capture keypress without focus I would like to know that as well.
    You can do this in C and C++ but I would like to just add it in to an existing java program, thanks.

  • Key event capture

    I can't find a way to capture the key events of the special key on multimedia keyboards, just like play/pause, browser or music..
    Any ideas?

    You probably can't. They have their own drivers to handle those specialties and Java (as far as I know) doesn't have support for those.

  • Fresh install, random 100% drive usage and system wide lag.

    Hi there, i just fresh installed Win 8.1 after having the issue of a svchost thrashing 100% disk access for minutes at a time and lagging whole system inc mouse pointer to the point that apps and games start to crash and the issue has not gone away. 
    I had also had the issue on old pc using different drives.
    This is the 4th system where ive seen this behaviour in Win 8 since launch and was wondering if there is a fix yet?  It happens on my 2 pc, my mothers laptop and a friends desktop, all with different hardware, 2 factory installs and 2x fresh installs
    from untouched iso's.
    It happens randomly when nothing is running on pc or sometimes when gaming or using apps and makes the desktop unresponsive for minutes at a time and sometimes crashes apps with it due to the system wide lag.  Even ctrl alt deleting can take several
    minutes for the menu to appear or even start Task Manager.
    Ive managed to catch 1/2 the issue with procmon but due to taking so long for apps to launch while the lag happens i can only get the last 1/2 of the trace which shows a mix between a svchost, explorer.exe and wmiprvse.exe thrashing the system to a standstill
    while accessing almost every file and reg key on the disk to over a million events recorded in procmon.
    IS there a fix for this or a way to check the procmon trace to see exactly what service or task is causing the thrashing?  I think whatever it is is buggy/broken, running at realtime and is blocking anything else from using the system until its done,
    which lags the system.
    Surely even an overloaded drive wouldnt cause other apps or the mouse to lag/hang so badly to the point of crashing and even Xp or Win 7 wouldnt lag/hang the desktop due to a busy drive.

    Gerg
    In order to diagnose your problem you will need to download and install the below
    Install the WPT (windows Performance Toolkit) http://social.technet.microsoft.com/wiki/contents/articles/4847.install-the-windows-performance-toolkit-wpt.aspx , 
    When you have open an elevated command prompt and type the following 
    WPRUI.exe (which is the windows performance recorder) and check off the boxes for the following
    First level triage, CPU usage, Disk IO.  If you problem is not CPU or HD then check off the relevant box/s as well (for example networking or registry)
    Let it run for 60 secs or more and save the file (it will show you where it is being saved and what the file is called
    Zip the file and upload to us on Onedrive (or any file sharing service) and give us a link to it in your next post.
    Wanikiya and Dyami--Team Zigzag

  • Global (system-wide) hotkey with Powershell

     
    Hi, i have a winform which is minimized/or hidden and would like to make it appear with a global (system wide) hotkey. (see bogus "new-hotkey"-cmdlet below)
    [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $form1 = New-Object 'System.Windows.Forms.Form'
    $form1.ClientSize = '300, 250'
    $form1.windowstate = "minimized"
    # -- bogus(!) code --
    $hk = new-hotkey -scope Global -keys "Ctrl,Shift,Z" -action ({$form1.windowstate = "normal" })
    $form1.ShowDialog()
    I searched the web intensively but only found C# solutions, which i could not translate into powershell (v3). I tried but it did not work:
    http://stackoverflow.com/questions/23855928/acessing-c-sharp-code-in-powershell
    The trouble is: even if i manage to use some C# code in my script, because i do not understand C#, i can't debug it.
    I tried a few third-party tools, like WASP, Pseventing, Autohotkey, but they all have disadvantages or did not work correctly, so using C# in Powershell is seemingly the way to go.
    I'm sorry, cause i know its not appreciated, but i need a working solution, not just tips how the get started.
    thanks a lot, Rob

    http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/ shows the basics of how to accomplish this, by using the Win32
    API RegisterHotKey function (which you've already found, by the looks of your StackOverflow post.)  Converting this to run PowerShell code in response to the hotkey might be a bit complicated, and also unnecessary in your case (since you seem to just
    want to change the value of a property on the form, you could do that right in the C# WndProc method, or whatever it calls in response to your hotkey.
    To make something more generic which can cause PowerShell code to execute, I'd probably have the form raise an event in response to the Windows message.  Then PowerShell scripts can use Register-ObjectEvent to respond to it, and you don't have to worry
    about problems with threads or runspaces (since the PowerShell engine already takes care of that for you when you use Register-ObjectEvent.)

  • Key events on the glasspane

    I'm trying to develop a glasspane that captures the key events as well as the mouse events.. In this example, the mouse events happen exactly the way I want them to, but I cannot for the life of me get a key event to register.. I've tried capturing keyTyped(), keyPressed(), and keyReleased() to no avail.. Dukes to whoever shows me the light,
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BCInv
        extends JFrame {
      JScrollPane jScrollPane1 = new JScrollPane();
      JTextArea jTextArea1 = new JTextArea();
      JScrollPane jScrollPane2 = new JScrollPane();
      JTable jTable1 = new JTable();
      JButton jButton1 = new JButton();
      public BCInv() {
        jbInit();
        setVisible(true);
        getGlassPane().setVisible(true);
        //here I'm adding both listeners in the same manner
        getGlassPane().addMouseListener(new BCInv_mouseAdapter());
        getGlassPane().addKeyListener(new BCInv_keyAdapter());
      public void jbInit() {
        setSize(new Dimension(611, 423));
        getContentPane().setLayout(null);
        jScrollPane1.setBounds(new Rectangle(9, 275, 574, 110));
        jTextArea1.setText("jTextArea1");
        jScrollPane2.setBounds(new Rectangle(10, 13, 573, 175));
        jButton1.setBounds(new Rectangle(196, 217, 89, 42));
        jButton1.setText("jButton1");
        this.getContentPane().add(jScrollPane1, null);
        this.getContentPane().add(jScrollPane2, null);
        this.getContentPane().add(jButton1, null);
        jScrollPane2.getViewport().add(jTable1, null);
        jScrollPane1.getViewport().add(jTextArea1, null);
      public static void main(String[] args) {
        BCInv BC = new BCInv();
      //this key stuff here never executes..
      void BCkey(KeyEvent e) {
        System.out.println("A key was typed: '"+e.getKeyChar()+"' = "+e.getKeyCode());
      class BCInv_keyAdapter extends java.awt.event.KeyAdapter {
        BCInv_keyAdapter() {}
        public void keyTyped(KeyEvent e) {
          BCkey(e);
      //All this mouse stuff works great..
      void BCmouseClicked(MouseEvent e) {
        System.out.println("click");
        Point glassPanePoint = e.getPoint();
        boolean inButton = false;
        boolean inMenuBar = false;
        Component component = null;
        Container container = getContentPane();
        Point containerPoint = SwingUtilities.convertPoint(
            getGlassPane(),
            glassPanePoint,
            getContentPane());
        component = SwingUtilities.getDeepestComponentAt(
            container,
            containerPoint.x,
            containerPoint.y);
        if (component == null) {
          return;
        System.out.println("underlying component="+component.toString());
      class BCInv_mouseAdapter
          extends java.awt.event.MouseAdapter {
        BCInv_mouseAdapter() {}
        public void mouseClicked(MouseEvent e) {
          BCmouseClicked(e);
    }

    * @author nordj
    public class GlassPane extends JPanel {
         private boolean okToLooseFocus = true;
         public GlassPane() {
              setName("GlassPane");
              setVisible(false);
              super.setOpaque(false);
              //super.setBackground(new Color(0x00,0x00,0x00,0x88));
              //super.setForeground(new Color(0x00,0x00,0x00,0xFF));
              // trap keyboard & mouse events.
              //enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
              enableEvents(0xFFFFFFFFFFFFFFFFl);
              setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              setInputVerifier(new GlassPaneInputVerifier());
         /* (non-Javadoc)
          * @see java.awt.Component#processMouseEvent(java.awt.event.MouseEvent)
         protected void processMouseEvent(MouseEvent e) {
              if (e.getID() == e.MOUSE_CLICKED) {
                   Toolkit.getDefaultToolkit().beep();
                   e.consume();
              super.processMouseEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#processKeyEvent(java.awt.event.KeyEvent)
         protected void processKeyEvent(KeyEvent e) {
              Toolkit.getDefaultToolkit().beep();
              super.processKeyEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#processEvent(java.awt.AWTEvent)
         protected void processEvent(AWTEvent e) {
              // TODO Auto-generated method stub
              //System.err.println(e);
              super.processEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#setVisible(boolean)
         public void setVisible(boolean visible) {
              okToLooseFocus = !visible;
              super.setVisible(visible);
              if (visible) {
                   requestFocusInWindow();
         /* (non-Javadoc)
          * @see java.awt.Component#paint(java.awt.Graphics)
         public void paint(Graphics g) {
              g.setColor(new Color(0xFF,0x00,0x00,0x88));
              g.fillRect(0,0,getWidth(), getHeight());
          * Simple hack to stop the RootPane loosing focus when it's visible
          * @author nordj
         private class GlassPaneInputVerifier extends InputVerifier {
              /* (non-Javadoc)
               * @see javax.swing.InputVerifier#verify(javax.swing.JComponent)
              public boolean verify(JComponent input) {
                   //return (!isVisible());
                   return okToLooseFocus;
    }

Maybe you are looking for