Procházet zdrojové kódy

Detect if we were double-clicked.

Because we are compiled as a console subsystem application, if the user
double-clicks the executable it will pop up a new console window.  Then,
since no arguments were passed, we will dump a usage message which the
user won't have time to read, and exit.

We now detect this situation and redirect the usage message to a popup.

There are three likely cases to handle.

If we are running in a service context there won't be a console window.
GetConsoleWindow() will return a null handle.

If were launched from a command window, the process ID owning the
console handle will be different from as our process ID.

If the process IDs are the same, we were started with a new console.  We
call FreeConsole() to close it and subsequently direct the usage message
to a message box.
Iain Patterson před 10 roky
rodič
revize
dd0e555ba8
2 změnil soubory, kde provedl 26 přidání a 3 odebrání
  1. 2 2
      event.cpp
  2. 24 1
      nssm.cpp

+ 2 - 2
event.cpp

@@ -80,12 +80,12 @@ int popup_message(unsigned int type, unsigned long id, ...) {
     return MessageBox(0, _T("The message which was supposed to go here is missing!"), NSSM, MB_OK | MB_ICONEXCLAMATION);
   }
 
-  TCHAR blurb[512];
+  TCHAR blurb[1024];
   va_start(arg, id);
   if (_vsntprintf_s(blurb, _countof(blurb), _TRUNCATE, format, arg) < 0) {
     va_end(arg);
     LocalFree(format);
-    return MessageBox(0, _T("the message which was supposed to go here is too big!"), NSSM, MB_OK | MB_ICONEXCLAMATION);
+    return MessageBox(0, _T("The message which was supposed to go here is too big!"), NSSM, MB_OK | MB_ICONEXCLAMATION);
   }
   va_end(arg);
 

+ 24 - 1
nssm.cpp

@@ -24,7 +24,8 @@ void strip_basename(TCHAR *buffer) {
 
 /* How to use me correctly */
 int usage(int ret) {
-  print_message(stderr, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_DATE);
+  if (GetConsoleWindow()) print_message(stderr, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_DATE);
+  else popup_message(MB_OK, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_DATE);
   return(ret);
 }
 
@@ -39,7 +40,29 @@ void check_admin() {
   FreeSid(AdministratorsGroup);
 }
 
+/* See if we were launched from a console window. */
+static void check_console() {
+  /* If we're running in a service context there will be no console window. */
+  HWND console = GetConsoleWindow();
+  if (! console) return;
+
+  unsigned long pid;
+  if (! GetWindowThreadProcessId(console, &pid)) return;
+
+  /*
+    If the process associated with the console window handle is the same as
+    this process, we were not launched from an existing console.  The user
+    probably double-clicked our executable.
+  */
+  if (GetCurrentProcessId() != pid) return;
+
+  /* We close our new console so that subsequent messages appear in a popup. */
+  FreeConsole();
+}
+
 int _tmain(int argc, TCHAR **argv) {
+  check_console();
+
   /* Remember if we are admin */
   check_admin();