Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

Programmatically Toggle Function Keys

$
0
0

Toggle Function Keys using Java

The function keys of the keyboard  Caps Lock, Num Lock and Scroll Locks keys can be turned on or off programmatically via the simple API available in the Toolkit class. This feature is very helpful in AWT/Swing based applications where we want data in certain format ex. all input must be in capital letter etc. or  we want the number pad be on for entering numeric data etc.

The following snippets shows  how to turn Caps Lock, Num Lock and Scroll Locks keys on or off via API.

<!--break-->

package com.livrona.snippets.util;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;

/**
* This snippet shows how to turn Caps Lock, Num Lock and Scroll Locks keys on
* or off via API.
*/

publicclass KeysToggler {

/**
* Where all the 3 keys Caps, Num and Scroll Lock on
*
* @return
*/

publicboolean areAllKeysOn() {
return numlock(true) && capslock(true) && scrolllock(true);
}

/**
* Where all the 3 keys Caps, Num and Scroll Lock off
*
* @return
*/

publicboolean areAllKeysOff() {
return numlock(false) && capslock(false) && scrolllock(false);
}

/**
* Turn Num Lock on or off
*
* @param b
* @return
*/

publicboolean numlock(boolean b) {
Toolkit tool = Toolkit.getDefaultToolkit();
try {
tool.setLockingKeyState(KeyEvent.VK_NUM_LOCK, b);
} catch (Exception e) {
returnfalse;
}
returntrue;
}

/**
* Turn Caps Lock on or off
*
* @param b
* @return
*/

publicboolean capslock(boolean b) {
Toolkit tool = Toolkit.getDefaultToolkit();
try {
tool.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, b);
} catch (Exception e) {
returnfalse;
}
returntrue;
}

/**
* Turn Scroll Lock on or off
*
* @param b
* @return
*/

publicboolean scrolllock(boolean b) {
Toolkit tool = Toolkit.getDefaultToolkit();
try {
tool.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, b);
} catch (Exception e) {
returnfalse;
}
returntrue;
}

/**
* Test Method
*
* @param args
* @throws Exception
*/

publicstaticvoid main(String[] args) throws Exception {
KeysToggler toggler =new KeysToggler();
toggler.numlock(true);
toggler.capslock(true);
toggler.scrolllock(true);

System.out.println("Are all keys on :"+ toggler.areAllKeysOn());

toggler.numlock(false);
toggler.capslock(false);
toggler.scrolllock(false);

System.out.println("Are all keys off :"+ toggler.areAllKeysOff());

}
}




Viewing all articles
Browse latest Browse all 178

Trending Articles