I'm tasked with creating a GUI for a multi-threaded C++ network server program that has it's main function running with a while loop that checks for keystrokes from the user. The C++ code for the loop is basically:
while(i!='q')
{
if(kbhit())
{
i=getch();
processkey(i);
}
}
And the processkey function performs different actions based on the key that was pressed.
I was reading up on ways to interface between Java and C/C++ and heard of JNI, but I also found someone who suggested using the Java Robot class to send the keystrokes from my GUI to the C++ program.
I've been trying to make a small test case application using the Robot class before trying to implement it in my larger project.
I created a program with a JFrame with two buttons, one starts a simple C++ program that loops, waiting for keypresses and which will close when 'q' is pressed, like my main program.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Runtime.getRuntime().exec("C:/Users/Administrator1/Desktop/Untitled2.exe");
// TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
The other button creates a Robot instance and tells that robot to send a key press of 'q', which should terminate the C++ program.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Robot robot = new Robot();
// Creates the delay of 5 sec so that you can open notepad before
// Robot start writting
//robot.delay(5000);
robot.keyPress(KeyEvent.VK_Q);
} catch (AWTException e) {
e.printStackTrace();
}
}
It isn't working though. Could it be because when the program is started from my Java app, it runs in the background rather than opening in a new command prompt window? Or is Robot not the way to go, and if so, are there any examples and/or tutorials online that could help me?