1

I have a Java program that continuously runs with the command prompt open. Now, if the user tries to exit the program either by pressing CTRL + C or by clicking on the close button, I want to display a confirmation if they really want to close.

If it is not possible using Java or batch, Any other way of doing it without using them?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
abhinav pandey
  • 574
  • 2
  • 8
  • 21
  • Pretty sure this is the same question as: http://stackoverflow.com/questions/1611931/catching-ctrlc-in-java – Andrew Stubbs Jul 18 '14 at 07:22
  • This link only catches ctrl + c I need to handle even if the user clicks on the close button. – abhinav pandey Jul 18 '14 at 07:27
  • It's not possible to handle that. You would have to write your own terminal, for example in Swing and check for a close operation. – Stefan Jul 18 '14 at 07:30
  • It is a console app. Any way of achieving it via CMD. I start the program using a batch file. Could I add something to it? – abhinav pandey Jul 18 '14 at 07:38
  • You could have a look at this post on SuperUser [Disable close button on DOS program in Windows 7](http://superuser.com/questions/731559/). I could not find the source and did not test it myself but the answer was accepted ... – Serge Ballesta Jul 18 '14 at 08:03

2 Answers2

2

This should be able to intercept the signal

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { /*
       my shutdown code here
    */ }
 });

More information here: How can I "intercept" Ctrl+C in a CLI application?

Community
  • 1
  • 1
Prashant
  • 190
  • 1
  • 9
0

As a complement to Prashant answer and to Disable close button on DOS program in Windows 7, I found some interesting elements on CodeProject Disable System Close Button on a Console Application.

If you can compile it (there are free C++ compilers all around) here is a C-C++ piece of code that you can include in your batch prior to you java program to disable the close button of the command window (this one has source and is tested ...) :

#include "windows.h"

int main(int argc, const char *argv[]) {
    HWND hWnd = ::GetConsoleWindow();
    if (hWnd != NULL) {
        HMENU hMenu = ::GetSystemMenu(hWnd, FALSE);
        if (hMenu != NULL) {
            ::DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
        }
    }
    return 0;
}

But beware when the close button is gone you must explicitely exit from the cmd ...

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252