I have a bat script which runs a java application. If I press ctrl+c on it, it the application terminates gracefully, invoking all the shutdown hooks. However, if I just clo
Further to the above answer of using SetConsoleCtrlHandler, you can also do this using JNA rather than writing your own native code.
You could create your own interface on kernel32 if you wanted, or use the one provided in this excellent framework: https://gitlab.com/axet/desktop
Some example code:
import com.github.axet.desktop.os.win.GetLastErrorException;
import com.github.axet.desktop.os.win.handle.HANDLER_ROUTINE;
import com.github.axet.desktop.os.win.libs.Kernel32Ex;
...
private static HANDLER_ROUTINE handler =
new HANDLER_ROUTINE()
{
@Override
public long callback(long dwCtrlType) {
if ((int)dwCtrlType == CTRL_CLOSE_EVENT) {
// *** do your shutdown code here ***
return 1;
}
return 0;
}
};
public static void assignShutdownHook() {
if (!Kernel32Ex.INSTANCE.SetConsoleCtrlHandler(handler, true))
throw new GetLastErrorException();
}
Note that I assigned the anonymous class to a field. I originally defined it in the call to SetConsoleCtrlHandler, but I think it was getting collected by the JVM.
Edit 4/9/17: Updated link from github to gitlab.