#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <windows.h>

#include "wincom.h"

static BOOL bLaunched;
static BOOL Opened = FALSE;
static HINSTANCE hInst;
static HWND hWnd;

HWND ConsoleGrab(VOID)
{
  HANDLE hConsoleOutput;
  CONSOLE_SCREEN_BUFFER_INFO csbi;

  if (Opened)
    return(hWnd);
  // Lets try a trick to determine if we were 'launched' as a seperate
  // screen, or just running from the command line.
  // We want to do this so that when we exit, we can prompt the user
  // before we shut down if we were 'launched'. Otherwise, any data on
  // the output window will be lost.
  // We will do this by simply getting the current cursor position. It
  // 'should' always be (0,0) on a launch, and something else if we were
  // executed as a command from a console window. The only time I can see
  // this as not working, is if the user executed a CLS and appended
  // our program with the '&' character, as in:
  //   C:\> CLS & ConGUI
  // This will also result in a (0,0) cursor pos, but in this case, the
  // user might also be wanting us to 'prompt' before closeing.
  // We also need to handle the case of:
  //   C:\> ConGUI > output.dat

  hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
  bLaunched = ((csbi.dwCursorPosition.X==0) && (csbi.dwCursorPosition.Y==0));
  if ((csbi.dwSize.X<=0) || (csbi.dwSize.Y <= 0)) bLaunched = FALSE;

  hInst = GetModuleHandle (NULL);
  hWnd = GetFocus();
  Opened = TRUE;
  return( hWnd);
}
VOID ConsoleRelease(VOID)
{
  if (!Opened)
    ConsoleGrab();
  if (bLaunched) {
    printf ("------------------------------------------\n");
    printf ("Program Finished - Hit <Enter> to continue");
    getchar();
	}
}

HINSTANCE ConsoleInst(VOID)
{
  if (!Opened)
    ConsoleGrab();
  return hInst;
}
BOOL CenterWindow (HWND hwnd)
{
  RECT    rect;
  int     w, h;
  int     wScreen, hScreen, xNew, yNew;
  HDC     hdc;

  GetWindowRect (hwnd, &rect);
  w = rect.right - rect.left;
  h = rect.bottom - rect.top;

  hdc = GetDC (hwnd);
  wScreen = GetDeviceCaps (hdc, HORZRES);
  hScreen = GetDeviceCaps (hdc, VERTRES);
  ReleaseDC (hwnd, hdc);

  xNew = wScreen/2 - w/2;
  yNew = hScreen/2 - h/2;
  return SetWindowPos (hwnd, NULL, xNew, yNew, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
void ConsoleTest()
{
   CenterWindow(ConsoleGrab());
   ConsoleRelease();
}
