SWT – How to capture keyboard event
In SWT, keyboard event is represent by KeyEvent class. We can use KeyListener to receive and process a KeyEvent.
The KeyEvent class has three member fields to provide information about the key that generated by event.
1) character – Display a char value of the pressed key.
2) stateMask – Check whether any other keys currently pressed. (common use to capture CTRL, ALT and SHIFT keys).
3) keyCode – Display a digit value of the pressed key.
We can attach a KeyListener() or KeyAdapter() to a widget control to keep track the keyboard event.
"widget control".addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { } });
Check whether ALT key is currently pressed
if ((e.stateMask & SWT.ALT) != 0)
Check whether BACKSPACE key is pressed
if(e.keyCode == SWT.BS)
P.S Please Check SWT class for other keyboard events.
Check whether any character is pressed
if(e.keyCode >=97 && e.keyCode <=122)
Check whether any digit is pressed
if(e.keyCode >=48 && e.keyCode <=57)
Here is the full source how to demonstrate how to capture the keyboard event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class SWTKeyEvent { public static void main (String [] args) { Display display = new Display (); Shell shell = new Shell(display); shell.setText("SWT KeyEvent Example"); shell.setLayout(new FillLayout()); Button button = new Button(shell, SWT.CENTER); button.setText("Type Something"); button.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { String string = ""; //check click together? if ((e.stateMask & SWT.ALT) != 0) string += "ALT - keyCode = " + e.keyCode; if ((e.stateMask & SWT.CTRL) != 0) string += "CTRL - keyCode = " + e.keyCode; if ((e.stateMask & SWT.SHIFT) != 0) string += "SHIFT - keyCode = " + e.keyCode; if(e.keyCode == SWT.BS) { string += "BACKSPACE - keyCode = " + e.keyCode; } if(e.keyCode == SWT.ESC) { string += "ESCAPE - keyCode = " + e.keyCode; } //check characters if(e.keyCode >=97 && e.keyCode <=122) { string += " " + e.character + " - keyCode = " + e.keyCode; } //check digit if(e.keyCode >=48 && e.keyCode <=57) { string += " " + e.character + " - keyCode = " + e.keyCode; } if(!string.equals("")) System.out.println (string); } }); shell.open(); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } display.dispose (); } } |
Hello!
How to use this code in VBA?
I want to listen keypress in Excel cell
Thanks!