Long story short, I am trying to write a Java program that gets input from and sends output to the Windows console (System.in, System.out). I need it to be aware of each keypress when it occurs, rather than after an entire line is returned.
I've been researching this for almost a week now, and it's impossible to do this with pure Java. It is, however, very simple to do in C.
This program compiles into a .exe file and sets the console mode so that input is returned character at a time as it is entered rather than line at a time.
#include <windows.h>
#define ENABLE_INSERT_MODE 0x0020
#define ENABLE_QUICK_EDIT_MODE 0x0040
#define ENABLE_EXTENDED_FLAGS 0x0080
void main()
{
HANDLE hStdin;
DWORD fdwMode;
hStdin = GetStdHandle(STD_INPUT_HANDLE);
fdwMode = ENABLE_INSERT_MODE || ENABLE_QUICK_EDIT_MODE || ENABLE_EXTENDED_FLAGS;
SetConsoleMode(hStdin, fdwMode);
}
Here is the Microsoft specifications for the function I used:
http://msdn2.microsoft.com/en-us/library/ms686033.aspx
I am hoping to use the JNI to call this function and give my Java program access to input one character at a time... but I am having trouble figuring out the details of the JNI. I have read a couple of tutorials on the JNI, but I am still quite confused as to exactly how it works.
Can someone give me some assistance in writing a Java method that will call that C program? From what I can tell, this should be a fairly easy thing to do. The Java program doesn't even need to interact with the C program at all... it just needs to run it so that the console can be put into character-at-a-time mode.
This is as close as I can get to what the code should look like. Can someone please give me a few pointers on how to get this C Program working with my Java program?
Thanks so much!
public class onechar{
// Main method gets input from System.in one char
// at a time and prints it to System.out
public static void main(String args[]){
System.loadLibrary("nativelib");
char c;
for(int i=0; i<5; i++){
try{
c = (char) System.in.read();
System.out.println(c);
}
catch(Exception ex){}
}
}
}