Click to See Complete Forum and Search --> : Ctrl-C in Java


Sanjeet Joshi
September 12th, 2000, 11:36 PM
Hi,

Can anyone tell me how to handle Ctrl-C in Java?

We have a window based application and before quting the application we need to logoff the user.
So even if the user presses Ctrl-C we need to capture it in order to logoff the user.

Cheers

Cheers
Sanjeet
----------------------------------------------------------------------------------------------
(Rating is not the reason I am here, but in general its a good practice to rate posts ;)

rums1976
September 14th, 2000, 02:45 PM
The following is a sample code which traps Ctrl-C. Use it appropriately to your needs.

import javax.swing.*;
import java.awt.event.*;
public class KeyTest extends JFrame {
public static void main(String[] args) {
KeyTest kt = new KeyTest();
// add Key Listener to your main window.
kt.addKeyListener((KeyListener) new CtrlCListener());
kt.addWindowListener((WindowListener)(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}));
kt.setBounds(0,0,100,100);
kt.setVisible(true);
}

KeyTest() {
JButton bt = new JButton("Some button");
getContentPane().add(bt);
}
}

class CtrlCListener extends KeyAdapter {
boolean ctrlOn = false;
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_CONTROL)
ctrlOn = true;
if(ke.getKeyCode() == KeyEvent.VK_C && ctrlOn) {
// Call your Log off method instead of this message
JOptionPane.showMessageDialog(null,"Hurray! you pressed Ctrl C");
ctrlOn = false;
}
}
}



rums1976

Sanjeet Joshi
September 14th, 2000, 09:48 PM
Thanks a lot for this solution.

But I want a solution that works on Windows and Unix both and according to Java Docs there
is no uniform platform independant solution to trap Ctrl+C (I read this after I posted this
question, off-course)

This will be good for windows only.
Let me know if I am wrong.

Anyway thanks a lot.


Cheers
Sanjeet
----------------------------------------------------------------------------------------------
(Rating is not the reason I am here, but in general its a good practice to rate posts ;)