WriteConsoleInput examples

Input / Output
Files, Registry, Streams In Gerneral

WriteConsoleInput examples

Postby Admin » Sun Nov 23, 2008 9:08 am

Code: Select all
#include <windows.h>
#include <stdio.h>
#include <conio.h>

DWORD WINAPI
InThread (void *pVoid);

void main ()
{
HANDLE hThread, hInput;
DWORD dwTID, dwTmp;

hThread = CreateThread (0, 0, (LPTHREAD_START_ROUTINE) InThread, 0,
0, & dwTID);
MessageBox (0, "Close Input Thread", "Test", MB_OK);

// Here we generate two input events: Esc key down and Esc key up
hInput = GetStdHandle (STD_INPUT_HANDLE);
INPUT_RECORD ir[2];

ir[0].EventType = KEY_EVENT;
ir[0].Event.KeyEvent.bKeyDown = TRUE;
ir[0].Event.KeyEvent.dwControlKeyState = 0;
ir[0].Event.KeyEvent.uChar.AsciiChar = 27;
ir[0].Event.KeyEvent.wRepeatCount = 1;
ir[0].Event.KeyEvent.wVirtualKeyCode = VK_ESCAPE;
ir[0].Event.KeyEvent.wVirtualScanCode = 27;
ir[1].EventType = KEY_EVENT;
ir[1].Event.KeyEvent.bKeyDown = FALSE;
ir[1].Event.KeyEvent.dwControlKeyState = 0;
ir[1].Event.KeyEvent.uChar.AsciiChar = 27;
ir[1].Event.KeyEvent.wRepeatCount = 1;
ir[1].Event.KeyEvent.wVirtualKeyCode = VK_ESCAPE;
ir[1].Event.KeyEvent.wVirtualScanCode = 27;
WriteConsoleInput (hInput, ir, 2, & dwTmp);

// Wait for the input thread to exit
WaitForSingleObject (hThread, INFINITE);

MessageBox (0, "Close App", "Test", MB_OK);
}

DWORD WINAPI
InThread (void *pVoid)
{
bool bExit = false;
int nChar=0;

while (nChar != 27)
{
nChar = getche ();
printf ("%c", nChar);
}
return 0;
}


Code: Select all
/******************************************************************************\
*       This is a part of the Microsoft Source Code Samples.
*       Copyright (C) 1993-1997 Microsoft Corporation.
*       All rights reserved.
*       This source code is only intended as a supplement to
*       Microsoft Development Tools and/or WinHelp documentation.
*       See these sources for detailed information regarding the
*       Microsoft samples programs.
\******************************************************************************/

#include <windows.h>
#include <memory.h>
#include <stdio.h>
#include <ctype.h>
#include "console.h"

#define MAX_MACRO_EVENTS 256
#define ALT_PRESSED (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
#define CONTROL_KEY (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | \
                     RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED | ENHANCED_KEY)

/************************************************************************
* FUNCTION: demoWriteIn(HANDLE hConOut)                                 *
*                                                                       *
* PURPOSE: demonstrate WriteConsoleInput by implementing a macro        *
*          recording facility that writes the recorded keystrokes to    *
*          the input queue for playback.                                *
*                                                                       *
* INPUT: the console buffer to record from and playback to              *
*                                                                       *
* RETURNS: none                                                         *
*************************************************************************/


void demoWriteIn(HANDLE hConOut)
{
  BOOL bSuccess;
  HANDLE hStdIn; /* standard input handle */
  INPUT_RECORD inputBuffer; /* buffer to hold a single console input record */
  INPUT_RECORD irMacroBuf[MAX_MACRO_EVENTS]; /* array of input events */
  DWORD dwInputEvents;
  DWORD dwBytesWritten, dwRecordsWritten;
  CHAR bOutBuf[256]; /* buffer to format event information into */
  BOOL bRecording = FALSE; /* TRUE if recording a macro */
  int iir = 0; /* index into macro input buffer */
  CHAR c;

  setConTitle(__FILE__);
  myPuts(hConOut, "\n\nLet's implement a simple macro record/playback facility.\n"
                  "Hit Alt+R to record, and Alt+P to playback. After turning\n"
                  "on Record mode, enter some keystrokes or mouse clicks.\n"
                  "Hit Alt+R to turn Record mode off, and Alt+P to playback\n"
                  "your keystrokes. I'll use the WriteConsoleInput API to\n"
                  "insert the recorded events into the input buffer.\n"
                  "Hit ESC at any time to return.");
  hStdIn = GetStdHandle(STD_INPUT_HANDLE);
  PERR(hStdIn != INVALID_HANDLE_VALUE, "GetStdHandle");
  for(;;)
    {
    /* if our macro event buffer is full, leave Record mode */
    if (iir == MAX_MACRO_EVENTS && bRecording)
      {
      bRecording = FALSE;
      putStatusLine(hConOut, "");
      }
    /* read an input event from the input event queue */
    bSuccess = ReadConsoleInput(hStdIn, &inputBuffer, 1, &dwInputEvents);
    PERR(bSuccess, "ReadConsoleInput");
    switch (inputBuffer.EventType)
      {
      case KEY_EVENT:
        if (inputBuffer.Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE)
          return;
        /* get the character that we read */
        c = inputBuffer.Event.KeyEvent.uChar.AsciiChar;
        if (!bRecording)
          {
          /* ignore key releases */
          if (!inputBuffer.Event.KeyEvent.bKeyDown)
            break;
          /* display the key event info on the status line */
          sprintf(bOutBuf, "key: virtual=%d ascii=%c",
              inputBuffer.Event.KeyEvent.wVirtualKeyCode, c);
          putStatusLine(hConOut, bOutBuf);
          /* if it's printable, and no control keys are down, show it */
          if (isprint(c) && !(inputBuffer.Event.KeyEvent.dwControlKeyState &
                CONTROL_KEY))
            {
            bSuccess = WriteFile(hConOut, &c, sizeof(c), &dwBytesWritten,
                NULL);
            PERR(bSuccess, "WriteFile");
            }
          /* is it an 'r' key? Is either the left or right ALT key down? */
          if (c == 'r' && (inputBuffer.Event.KeyEvent.dwControlKeyState &
              (ALT_PRESSED)))
            {
            bRecording = TRUE;
            iir = 0; /* reset macro buffer pointer to beginning */
            putStatusLine(hConOut, "RECORDING...");
            }
          /* is it a 'p' key? Is either the left of right ALT key down? */
          if (c == 'p' && (inputBuffer.Event.KeyEvent.dwControlKeyState &
              (ALT_PRESSED)))
            {
            /* stuff all the input events into the input buffer */
            bSuccess = WriteConsoleInput(hStdIn, /* console input buffer */
                irMacroBuf, /* address of the buffer for write data */
                iir, /* number of records to write */
                &dwRecordsWritten); /* returns number of records written */
            PERR(bSuccess, "WriteConsoleInput");
            }
          }
        else /* we're recording */
          {
          if (inputBuffer.Event.KeyEvent.bKeyDown)
            {
            /* is it an 'r' key? Is either the left or right ALT key down? */
            if (c == 'r' && (inputBuffer.Event.KeyEvent.dwControlKeyState &
                (ALT_PRESSED)))
              {
              bRecording = FALSE;
              putStatusLine(hConOut, "");
              break;
              }
            /* we need to ignore the 'playback' keystroke or we'll */
            /* automatically start playing back during playback! */
            if (c == 'p' && (inputBuffer.Event.KeyEvent.dwControlKeyState &
                (ALT_PRESSED)))
              break;
            /* if it's printable, and no control keys are down, show it */
            if (isprint(c) && !(inputBuffer.Event.KeyEvent.dwControlKeyState &
                CONTROL_KEY))
              {
              bSuccess = WriteFile(hConOut, &c, sizeof(c), &dwBytesWritten,
                  NULL);
              PERR(bSuccess, "WriteFile");
              }
            }
          /* store the key event in the macro buffer */
          memcpy(&irMacroBuf[iir++], &inputBuffer, sizeof(inputBuffer));
          } /* else */
        break;
      case MOUSE_EVENT:
        if (!bRecording)
          {
          sprintf(bOutBuf, "mouse: %s at %d, %d",
              (inputBuffer.Event.MouseEvent.dwEventFlags == MOUSE_MOVED ?
              "moved" : "clicked"), inputBuffer.Event.MouseEvent.dwMousePosition.X,
              inputBuffer.Event.MouseEvent.dwMousePosition.Y);
          putStatusLine(hConOut, bOutBuf);
          }
        else /* copy the mouse event into the macro buffer */
          memcpy(&irMacroBuf[iir++], &inputBuffer, sizeof(inputBuffer));
        break;
      case WINDOW_BUFFER_SIZE_EVENT:
        if (!bRecording)
          {
          sprintf(bOutBuf, "window: %d, %d",
              inputBuffer.Event.WindowBufferSizeEvent.dwSize.X,
              inputBuffer.Event.WindowBufferSizeEvent.dwSize.Y);
          putStatusLine(hConOut, bOutBuf);
          Sleep(1000);
          }
        break;
      } /* switch */
    } /* while */
  return;
}

Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

Re: WriteConsoleInput examples

Postby Admin » Sun Nov 23, 2008 9:10 am

Code: Select all
#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#define VK_A 0x41
#define MAPVK_VK_TO_VSC 0
DWORD WINAPI test(LPVOID lp)
{
system("edit");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hConIn = CreateFile(L"CONIN$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
DWORD dwTmp;
CreateThread(NULL, 0, test, (LPDWORD)0, 0, &dwTmp);
Sleep( 1000 );
INPUT_RECORD ir[2];
ir[0].EventType = KEY_EVENT;
ir[0].Event.KeyEvent.bKeyDown = TRUE;
ir[0].Event.KeyEvent.dwControlKeyState = 0;
ir[0].Event.KeyEvent.uChar.UnicodeChar = 'a';
ir[0].Event.KeyEvent.wRepeatCount = 1;
ir[0].Event.KeyEvent.wVirtualKeyCode = VK_A;
ir[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_A, MAPVK_VK_TO_VSC);
ir[1].EventType = KEY_EVENT;
ir[1].Event.KeyEvent.bKeyDown = FALSE;
ir[1].Event.KeyEvent.dwControlKeyState = 0;
ir[1].Event.KeyEvent.uChar.UnicodeChar = 'a';
ir[1].Event.KeyEvent.wRepeatCount = 1;
ir[1].Event.KeyEvent.wVirtualKeyCode = VK_A;
ir[1].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_A, MAPVK_VK_TO_VSC);
WriteConsoleInput (hConIn, ir, 2, &dwTmp);

Sleep(1000);
return 0;
}
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

Re: WriteConsoleInput examples

Postby Admin » Wed Nov 26, 2008 12:33 am

Code: Select all
//------------Sample using CreateProcess and Anonymous Pipes-----------------
//---------------------childspawn.cpp----------------------------------------
//---------------------use freely--------------------------------------------
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#pragma hdrstop
#include <condefs.h>

#define bzero(a) memset(a,0,sizeof(a)) //easier -- shortcut

bool IsWinNT()  //check if we're running NT
{
  OSVERSIONINFO osv;
  osv.dwOSVersionInfoSize = sizeof(osv);
  GetVersionEx(&osv);
  return (osv.dwPlatformId == VER_PLATFORM_WIN32_NT);
}

void ErrorMessage(char *str)  //display detailed error info
{
  LPVOID msg;
  FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &msg,
    0,
    NULL
  );
  printf("%s: %s\n",str,msg);
  LocalFree(msg);
}

//---------------------------------------------------------------------------
void main()
{
  char buf[1024];           //i/o buffer

  STARTUPINFO si;
  SECURITY_ATTRIBUTES sa;
  SECURITY_DESCRIPTOR sd;               //security information for pipes
  PROCESS_INFORMATION pi;
  HANDLE newstdin,newstdout,read_stdout,write_stdin;  //pipe handles

  if (IsWinNT())        //initialize security descriptor (Windows NT)
  {
    InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, true, NULL, false);
    sa.lpSecurityDescriptor = &sd;
  }
  else sa.lpSecurityDescriptor = NULL;
  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.bInheritHandle = true;         //allow inheritable handles

  if (!CreatePipe(&newstdin,&write_stdin,&sa,0))   //create stdin pipe
  {
    ErrorMessage("CreatePipe");
    getch();
    return;
  }
  if (!CreatePipe(&read_stdout,&newstdout,&sa,0))  //create stdout pipe
  {
    ErrorMessage("CreatePipe");
    getch();
    CloseHandle(newstdin);
    CloseHandle(write_stdin);
    return;
  }

  GetStartupInfo(&si);      //set startupinfo for the spawned process
  /*
  The dwFlags member tells CreateProcess how to make the process.
  STARTF_USESTDHANDLES validates the hStd* members. STARTF_USESHOWWINDOW
  validates the wShowWindow member.
  */
  si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_HIDE;
  si.hStdOutput = newstdout;
  si.hStdError = newstdout;     //set the new handles for the child process
  si.hStdInput = newstdin;
  char app_spawn[] = "d:\\winnt\\system32\\cmd.exe"; //sample, modify for your
                                                     //system

  //spawn the child process
  if (!CreateProcess(app_spawn,NULL,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,
                     NULL,NULL,&si,π))
  {
    ErrorMessage("CreateProcess");
    getch();
    CloseHandle(newstdin);
    CloseHandle(newstdout);
    CloseHandle(read_stdout);
    CloseHandle(write_stdin);
    return;
  }

  unsigned long exit=0;  //process exit code
  unsigned long bread;   //bytes read
  unsigned long avail;   //bytes available

  bzero(buf);
  for(;;)      //main program loop
  {
    GetExitCodeProcess(pi.hProcess,&exit);      //while the process is running
    if (exit != STILL_ACTIVE)
      break;
    PeekNamedPipe(read_stdout,buf,1023,&bread,&avail,NULL);
    //check to see if there is any data to read from stdout
    if (bread != 0)
    {
      bzero(buf);
      if (avail > 1023)
      {
        while (bread >= 1023)
        {
          ReadFile(read_stdout,buf,1023,&bread,NULL);  //read the stdout pipe
          printf("%s",buf);
          bzero(buf);
        }
      }
      else {
        ReadFile(read_stdout,buf,1023,&bread,NULL);
        printf("%s",buf);
      }
    }
    if (kbhit())      //check for user input.
    {
      bzero(buf);
      *buf = (char)getche();
      //printf("%c",*buf);
      WriteFile(write_stdin,buf,1,&bread,NULL); //send it to stdin
      if (*buf == '\r') {
        *buf = '\n';
        printf("%c",*buf);
        WriteFile(write_stdin,buf,1,&bread,NULL); //send an extra newline char,
                                                  //if necessary
      }
    }
  }
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  CloseHandle(newstdin);            //clean stuff up
  CloseHandle(newstdout);
  CloseHandle(read_stdout);
  CloseHandle(write_stdin);
}
//----------------------------EOF--------------------------------------------
//---------------------------------------------------------------------------
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

Re: WriteConsoleInput examples

Postby Admin » Wed Nov 26, 2008 12:38 am

Code: Select all
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998  Paul Brannan
//Copyright (C) 1998  I.Ioannou
//Copyright (C) 1997  Brad Johnson
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//roryt@hol.gr
//
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
// Module:      tncon.cpp
//
// Contents:   telnet console processing
//
// Product:      telnet
//
// Revisions: August 30, 1998 Paul Brannan <pbranna@clemson.edu>
//            July 29, 1998 Paul Brannan
//            June 15, 1998 Paul Brannan
//            May 16, 1998 Paul Brannan
//            5.April.1997 jbj@chrysalis.org
//            9.Dec.1996 jbj@chrysalis.org
//            Version 2.0
//
//            02.Apr.1995   igor.milavec@uni-lj.si
//                 Original code
//
///////////////////////////////////////////////////////////////////////////////
#include "tncon.h"
#include "keytrans.h"
#include "ttelhndl.h"
#include "tconsole.h"

#define KEYEVENT InputRecord[i].Event.KeyEvent

// Paul Brannan 6/25/98
// #ifdef __MINGW32__
// #define KEYEVENT_CHAR KEYEVENT.AsciiChar
// #else
#define KEYEVENT_CHAR KEYEVENT.uChar.AsciiChar
// #endif

#define KEYEVENT_PCHAR &KEYEVENT_CHAR

// This is for local echo (Paul Brannan 5/16/98)
inline void DoEcho(const char *p, int l, TConsole &Console,
               TNetwork &Network, NetParams *pParams) {
   // Pause the console (Paul Brannan 8/24/98)
   if(Network.get_local_echo()) {
      ResetEvent(pParams->hUnPause);
      SetEvent(pParams->hPause);
      while (!*pParams->bNetPaused); // Pause

      Console.WriteStringFast(p, l);

      SetEvent(pParams->hUnPause); // Unpause
   }
}

// Paul Brannan 5/27/98
// Fixed this code for use with appliation cursor keys
// This should probably be optimized; it's pretty ugly as it is
char *FindClosestKey(WORD keyCode, DWORD keyState, KeyTranslator &KeyTrans) {
   char *p;
   
   // keyState &= ~NUMLOCK_ON;      // ignore numlock
   // keyState &= ~SCROLLLOCK_ON;      // ignore scroll lock

   // Paul Brannan 7/20/98
   if(ini.get_alt_erase()) {
      if(keyCode == VK_BACK) {
         keyCode = VK_DELETE;
         keyState |= ENHANCED_KEY;
      } else if(keyCode == VK_DELETE && (keyState & ENHANCED_KEY)) {
         keyCode = VK_BACK;
         keyState &= ~ENHANCED_KEY;
      }
   }

   DWORD ext_mode = KeyTrans.get_ext_mode();
   if(ext_mode) {
      if(ext_mode & APP3_KEY) {
         keyState |= APP3_KEY; // Try with vt52 mode
         if(p = KeyTrans.TranslateKey(keyCode, keyState)) return p;

         // Check numlock and scroll lock (Paul Brannan 9/23/98)
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~NUMLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~NUMLOCK_ON)) return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~SCROLLLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~SCROLLLOCK_ON)) return p;

         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~CAPSLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~CAPSLOCK_ON)) return p;

         keyState &= ~APP3_KEY; // Now try without vt52 mode
      }
      if(ext_mode & APP2_KEY) {
         keyState |= APP2_KEY; // Try with vt52 mode
         if(p = KeyTrans.TranslateKey(keyCode, keyState)) return p;

         // Check numlock and scroll lock (Paul Brannan 9/23/98)
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~NUMLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~NUMLOCK_ON)) return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~SCROLLLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~SCROLLLOCK_ON)) return p;

         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~CAPSLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~CAPSLOCK_ON)) return p;

         keyState &= ~APP2_KEY; // Now try without vt52 mode
      }
      if(ext_mode & APP_KEY) {
         keyState |= APP_KEY; // Try with application cursor key mode
         if(p = KeyTrans.TranslateKey(keyCode, keyState)) return p;

         // Check numlock and scroll lock (Paul Brannan 9/23/98)
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~NUMLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~NUMLOCK_ON)) return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~SCROLLLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~SCROLLLOCK_ON)) return p;

         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~CAPSLOCK_ON))
            return p;
         if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
            & ~CAPSLOCK_ON)) return p;
         
         keyState &= ~APP_KEY; // Now try without app cursor key mode
      }
   }
   if(p = KeyTrans.TranslateKey(keyCode, keyState)) return p;

   // Check numlock and scroll lock (Paul Brannan 9/23/98)
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~NUMLOCK_ON)) return p;
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
      & ~NUMLOCK_ON)) return p;
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~SCROLLLOCK_ON)) return p;
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
      & ~SCROLLLOCK_ON)) return p;

   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY)) return p;
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~CAPSLOCK_ON)) return p;
   if(p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
      & ~CAPSLOCK_ON)) return p;

   return NULL; // we couldn't find a suitable key translation
}

int telProcessConsole(NetParams *pParams, KeyTranslator &KeyTrans,
                 TConsole &Console, TNetwork &Network, TMouse &Mouse,
                 Tnclip &Clipboard, HANDLE hThread)
{
   char * p;
   int i;
   //  printf("telProcessConsole()\n");
   HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
   
   SetConsoleMode(hConsole, ini.get_enable_mouse() ? ENABLE_MOUSE_INPUT : 0);
   
   const DWORD nHandle = 2;
   HANDLE hHandle[nHandle] = {hConsole, pParams->hExit};
   
   for (;;) {
      DWORD dwInput;
      switch (WaitForMultipleObjects(nHandle, hHandle, FALSE, INFINITE)) {
        case WAIT_OBJECT_0: {

         // Paul Brannan 7/29/98
         if(ini.get_input_redir()) {
            char InputBuffer[10];
            if(!ReadFile(hConsole, InputBuffer, 10, &dwInput, NULL))
               return TNNOCON;
            // no key translation for redirected input
            Network.WriteString(InputBuffer, dwInput);
            break;
         }

         INPUT_RECORD InputRecord[11];
         if (!ReadConsoleInput(hConsole, &InputRecord[0], 10, &dwInput))
            return TNPROMPT;
         // The (unsigned) gets rid of a compiler warning (Paul Brannan 5/25/98)
         for (i = 0; (unsigned)i < dwInput; i++){
            switch (InputRecord[i].EventType) {
            case KEY_EVENT:{
               if (KEYEVENT.bKeyDown) {
                  // Modified to use redefinable keys (Paul Brannan 5/30/98)
                  if (KEYEVENT.dwControlKeyState &
                     (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) {

                     if(KEYEVENT_CHAR == ini.get_escape_key())
                        return TNPROMPT;
                     else if(KEYEVENT_CHAR == ini.get_scrollback_key())
                        return TNSCROLLBACK;
                     else if(KEYEVENT_CHAR == ini.get_dial_key())
                        return TNSPAWN;
                  }
                  if (KEYEVENT.dwControlKeyState & SHIFT_PRESSED) {
                     if(KEYEVENT_CHAR == VK_INSERT) {
                        if(ini.get_keyboard_paste()) {
                           Clipboard.Paste();
                           break;
                        }
                     }
                  }

                  //
                  //    John Ioannou (roryt@hol.gr)
                  //   Athens 31/03/97 00:25am GMT+2
                  //   fix for win95 CAPSLOCK bug
                  //   first check if the user has keys with capslock
                  //   and then wee filter it
                  //
                  WORD  keyCode  = KEYEVENT.wVirtualKeyCode;
                  DWORD keyState = KEYEVENT.dwControlKeyState;
                  
                  // Paul Brannan 5/27/98
                  // Moved the code that was here to FindClosestKey()
                  p = FindClosestKey(keyCode, keyState, KeyTrans);
                  
                  if (p == NULL) // if we don't have a translator
                  {
                     if (KEYEVENT_CHAR) {
                        Network.WriteString(KEYEVENT_PCHAR, 1);
                        // Local echo (Paul Brannan 5/16/98)
                        DoEcho(KEYEVENT_PCHAR, 1,
                           Console, Network, pParams);
                     }
                  }
                  else
                  {
                     Network.WriteString(p, strlen(p));
                     // Local echo (Paul Brannan 5/16/98)
                     DoEcho(p, strlen(p), Console, Network, pParams);
                  }
               }
                        }
               break;

            case MOUSE_EVENT:
               if(!InputRecord[i].Event.MouseEvent.dwEventFlags) {
                  // *pParams->bNetPause = 1;      // pause incoming thread
                  ResetEvent(pParams->hUnPause);
                  SetEvent(pParams->hPause);
                  while (!*pParams->bNetPaused);   // thread paused
                  // SuspendThread(hThread);

                  // Put the mouse's X and Y coords back into the
                  // input buffer
                  DWORD Result;
                  WriteConsoleInput(hConsole, &InputRecord[i], 1,
                     &Result);

                  Mouse.doMouse();

                  // *pParams->bNetPause = 0;
                  SetEvent(pParams->hUnPause);
                  // ResumeThread(hThread);
               }
               break;

            }
         
         } // keep going until no more input
         break;
                     }
        default:
         return TNNOCON;
      }
   }
}

WORD scrollkeys (){
   HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
   INPUT_RECORD InputRecord;
   BOOL done = FALSE;
   
   while (!done) {
      DWORD dwInput;
      WaitForSingleObject( hConsole, INFINITE );
      if (!ReadConsoleInput(hConsole, &InputRecord, 1, &dwInput)){
         done = TRUE;
         continue;
      }
      if (InputRecord.EventType == KEY_EVENT &&
         InputRecord.Event.KeyEvent.bKeyDown ) {
         // Why not just return the key code?  (Paul Brannan 12/5/98)
         return InputRecord.Event.KeyEvent.wVirtualKeyCode;
//         switch (InputRecord.Event.KeyEvent.wVirtualKeyCode){
//         case VK_ESCAPE:
//         case VK_UP:
//         case VK_DOWN:
//         case VK_NEXT:
//         case VK_PRIOR:
//         case VK_TAB:
//            return InputRecord.Event.KeyEvent.wVirtualKeyCode;
//         case VK_RIGHT:
//            break;
//         case VK_LEFT:
//            break;
//         case VK_DELETE:
//            break;
//         case VK_BACK:
//            break;
//            
//         default:
//            break;
//         }
      } else if(InputRecord.EventType == MOUSE_EVENT) {
         if(!InputRecord.Event.MouseEvent.dwEventFlags) {
            // Put the mouse's X and Y coords back into the input buffer
            WriteConsoleInput(hConsole, &InputRecord, 1, &dwInput);
            return SC_MOUSE;
         }
      }
   }
   return SC_ESC;
}

// Thomas Briggs 8/17/98
BOOL WINAPI ControlEventHandler(DWORD event) {
   switch(event) {
   case CTRL_BREAK_EVENT:
      return TRUE;
   default:
      return FALSE;
   }
}
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

Re: WriteConsoleInput examples

Postby Admin » Mon Dec 01, 2008 11:42 am

Code: Select all
// Server.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <tchar.h>
#include <string.h>
#include <stdio.h>
#include <winsock.h>
#include <iostream>
using namespace std;
#pragma comment( lib, "wsock32.lib" )

#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 25

int InitSocket(int nPort);
int SendData(SOCKET sock, char * lpszData);
LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int HandleData(WPARAM wParam, LPARAM lParam);
int HandleAccept(WPARAM wParam, LPARAM lParam);

   sockaddr_in LocalSin;
   sockaddr_in RemoteSin;
   SOCKET      Sock;
   HWND      hWnd;
   HINSTANCE   hInst;
   HANDLE      rPipe;
   HANDLE      wPipe;

STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
DWORD WINAPI CreateConsole(LPVOID lp)
{

   SECURITY_ATTRIBUTES secattr;
   ZeroMemory(&secattr,sizeof(secattr));
   secattr.nLength = sizeof(secattr);
   secattr.bInheritHandle = TRUE;

   //Create pipes to write and read data
   CreatePipe(&rPipe,&wPipe,&secattr,0);
   //
   
   ZeroMemory(&sInfo,sizeof(sInfo));
   
   ZeroMemory(&pInfo,sizeof(pInfo));
   sInfo.cb=sizeof(sInfo);
   sInfo.dwFlags=STARTF_USESTDHANDLES;
   sInfo.hStdInput=NULL;
   sInfo.hStdOutput=wPipe;
   sInfo.hStdError=wPipe;
   
   CreateProcess(0, "cmd.exe",0,0,TRUE,NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
   //CloseHandle(wPipe);

   
   char buf[1024];
   char tmpbuf[128];
     DWORD reDword = 128;
     BOOL res;
     do
     {
      Sleep(1000); //ReadFile takes time..
      res=ReadFile(rPipe,tmpbuf,128,&reDword,0);
      tmpbuf[reDword] = '\0';
      strncat(buf,tmpbuf,reDword);
      //MessageBox(0,LPCSTR(tmpbuf),0,0);
        //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
     }while (reDword == 128);
   //MessageBox(0,buf,0,0);
   SendData(Sock, buf);
   return 0;
}

void WriteToConsole(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   //HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);
      
      
      char buf[1024];
      char tmpbuf[128];
      DWORD reDword = 128;
      BOOL res;
      do
      {
         Sleep(1000); //ReadFile takes time..
         res=ReadFile(rPipe,tmpbuf,128,&reDword,0);
         tmpbuf[reDword] = '\0';
         strncat(buf,tmpbuf,reDword);
         //MessageBox(0,LPCSTR(tmpbuf),0,0);
         //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
      }while (reDword == 128);
      //MessageBox(0,buf,0,0);
      SendData(Sock, buf);

      return;
      }
      
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}

void WriteToConsoleOLD(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);
      
      
      char buf[1024];
      char tmpbuf[128];
      DWORD reDword = 128;
      BOOL res;
      do
      {
         Sleep(1000); //ReadFile takes time..
         res=ReadFile(hConOut,tmpbuf,128,&reDword,0);
         tmpbuf[reDword] = '\0';
         strncat(buf,tmpbuf,reDword);
         //MessageBox(0,LPCSTR(tmpbuf),0,0);
         //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
      }while (reDword == 128);
      //MessageBox(0,buf,0,0);
      SendData(Sock, buf);

      return;
      }
      
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}


int InitSocket(int nPort)
{

   LocalSin.sin_family = AF_INET;
   LocalSin.sin_port = 0;
   
   RemoteSin.sin_family = AF_INET;
   RemoteSin.sin_port = htons(nPort);

   if ((RemoteSin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")) == INADDR_NONE)
      return false;      // Error setting IP

   if ((Sock = socket(PF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
      return false;      // Error creating socket

   if (bind(Sock, (sockaddr *)&LocalSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;      // Error binding socket

   if (connect(Sock, (sockaddr *)&RemoteSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;

   WSAAsyncSelect(Sock, hWnd, WM_USER + 2, FD_READ | FD_CLOSE);

   return TRUE;
}

int SendData(SOCKET sock, char * lpszData)
{
   return send(sock, lpszData, strlen(lpszData), 0);
}

LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   switch (uMsg)
   {
   case WM_DESTROY:
      PostQuitMessage(0);
      break;

   case WM_USER + 2:
      HandleData(wParam, lParam);
      break;
   }

   return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

int HandleData(WPARAM wParam, LPARAM lParam)
{
   SOCKET sock = (SOCKET)wParam;
   WORD event = LOWORD(lParam);
   WORD error = HIWORD(lParam);

   if (event == FD_CLOSE)
   {
        closesocket(sock);
      PostQuitMessage(0);
   }
   else if (event == FD_READ)
   {
      char szBuffer[1024];
      ZeroMemory(szBuffer, 1024);
      recv(sock, szBuffer, 1024, 0);

      //MessageBox(hWnd, szBuffer, "Received Data!", MB_OK);
     WriteToConsole(szBuffer);

      //closesocket(sock);
   }
   return TRUE;
}   

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

   WSAData wsa;
   WSAStartup(MAKEWORD(1, 1), &wsa);

   WNDCLASS wnd;
   wnd.cbClsExtra = 0;
   wnd.cbWndExtra = 0;
   wnd.hbrBackground = (HBRUSH) COLOR_WINDOW;
   wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
   wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION);
   wnd.hInstance = hInst;
   wnd.lpfnWndProc = WinProc;
   wnd.lpszClassName = "GenericClientClass";
   wnd.lpszMenuName = NULL;
   wnd.style = CS_HREDRAW | CS_VREDRAW;

   RegisterClass(&wnd);

   hWnd = CreateWindow("GenericClientClass", "Connecting to port 6666...", WS_CAPTION | WS_POPUPWINDOW, 0, 100, 200, 100, NULL, NULL, hInst, NULL);

   if (!hWnd)
     return -2;

   ShowWindow(hWnd, SW_SHOWNORMAL);

   if (!InitSocket(6666))
   {
     char szBuffer[1024];
 
     sprintf(szBuffer, "Error connecting [%d]", WSAGetLastError());

     MessageBox(hWnd, szBuffer, "Error", MB_OK);
 
     DestroyWindow(hWnd);
   }

   AllocConsole();
   
   CreateThread(NULL, 0, CreateConsole, (LPDWORD)0, 0, 0);

   MSG msg;

   while (GetMessage(&msg, NULL, 0, 0))
   {
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }

   WSACleanup();

   return msg.wParam;
}

void old(void) {

/*
local_info.sin_family = AF_INET;
      local_info.sin_port = htons(cc_port);
      local_info.sin_addr.s_addr = htons(INADDR_ANY);
     
      std::cout << "attempting to bind... ";
      if(bind(sock, (SOCKADDR*) &local_info, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to prepare socket for listening... ";
      if(listen(sock, 5) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to listen for a connection";
      do
      {
            tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
            std::cout << "!";
      }
      while(tmp_sock == SOCKET_ERROR);
      std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

      closesocket(sock);
      closesocket(tmp_sock);

  */


   //AllocConsole();
   //HWND hwnd = GetConsoleWindow();
   //if (hwnd)
   {
      //console.Attach(hwnd);
      //console.ShowWindow(SW_HIDE);
   }
}
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

Re: WriteConsoleInput examples

Postby Admin » Mon Dec 01, 2008 2:51 pm

Code: Select all
http://msdn.microsoft.com/en-us/library/ms971319.aspx

Code: Select all
'courier for textbox 2 width = 8535 height is 2655
Private Sub Form_Load()
Winsock1.LocalPort = 6666
Winsock1.Listen
End Sub

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
    Winsock1.SendData Text1.Text
    Text1.Text = ""
End If
End Sub

Private Sub Winsock1_Close()
Winsock1.Close
Winsock1.Listen
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
Winsock1.Close
Winsock1.Accept requestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData Data, vbString
Debug.Print Data
Text2.Text = Text2.Text & vbCrLf & Data
Text2.SelStart = Len(Text2.Text)
End Sub

Code: Select all
// Server.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <tchar.h>
#include <string.h>
#include <stdio.h>
#include <winsock.h>
#include <iostream>
#include <winable.h> //SetWinHook?
#include <sstream> //DbgOutInt
#include "CrtDbg.h" //Debug
using namespace std;
#pragma comment( lib, "wsock32.lib" )

#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 25
//http://msdn.microsoft.com/en-us/library/ms971319.aspx
#define  EVENT_CONSOLE_CARET            0x4001
#define  EVENT_CONSOLE_UPDATE_REGION      0x4002
#define  EVENT_CONSOLE_UPDATE_SIMPLE      0x4003
#define  EVENT_CONSOLE_UPDATE_SCROLL      0x4004
#define  EVENT_CONSOLE_LAYOUT            0x4005
#define  EVENT_CONSOLE_START_APPLICATION      0x4006
#define  EVENT_CONSOLE_END_APPLICATION      0x4007

int InitSocket(int nPort);
int SendData(SOCKET sock, char * lpszData);
LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int HandleData(WPARAM wParam, LPARAM lParam);
int HandleAccept(WPARAM wParam, LPARAM lParam);

   sockaddr_in LocalSin;
   sockaddr_in RemoteSin;
   SOCKET      Sock;
   HWND      hWnd;
   HINSTANCE   hInst;
   HANDLE      rPipe;
   HANDLE      wPipe;
   int         p=0;

STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
DWORD WINAPI CreateConsole(LPVOID lp)
{

   SECURITY_ATTRIBUTES secattr;
   ZeroMemory(&secattr,sizeof(secattr));
   secattr.nLength = sizeof(secattr);
   secattr.bInheritHandle = TRUE;

   //Create pipes to write and read data
   CreatePipe(&rPipe,&wPipe,&secattr,0);
   //
   
   ZeroMemory(&sInfo,sizeof(sInfo));
   
   ZeroMemory(&pInfo,sizeof(pInfo));
   sInfo.cb=sizeof(sInfo);
   //sInfo.dwFlags=STARTF_USESTDHANDLES;
   //sInfo.hStdInput=NULL;
   //sInfo.hStdOutput=wPipe;
   //sInfo.hStdError=wPipe;
   //CreateProcess(0, "cmd.exe",0,0,TRUE,NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
   CreateProcess(0, "cmd.exe",0,0,TRUE,0,0,0,&sInfo,&pInfo);
   //CloseHandle(wPipe);

   return 0;
   char buf[1024];
   char tmpbuf[128];
     DWORD reDword = 128;
     BOOL res;
     do
     {
      Sleep(1000); //ReadFile takes time..
      res=ReadFile(rPipe,tmpbuf,128,&reDword,0);
      tmpbuf[reDword] = '\0';
      strncat(buf,tmpbuf,reDword);
      //MessageBox(0,LPCSTR(tmpbuf),0,0);
        //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
     }while (reDword == 128);
   //MessageBox(0,buf,0,0);
   SendData(Sock, buf);
   return 0;
}

void WriteToConsole(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);

     /*
      Sleep(1000);
      //CONSOLE_SCREEN_BUFFER_INFO bInfo;
      //CHAR_INFO buffer[30];
     
      char buf[1024];
      char tmpbuf[128];
     DWORD reDword = 128;
     BOOL res;
     do
     {
      Sleep(1000); //ReadFile takes time..
      res=ReadFile(hConOut,tmpbuf,128,&reDword,0);
      tmpbuf[reDword] = '\0';
      strncat(buf,tmpbuf,reDword);
      //MessageBox(0,LPCSTR(tmpbuf),0,0);
        //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
     }while (reDword == 128);
   MessageBox(0,buf,0,0);
      */
      /*
      SMALL_RECT readRegion = {0,0,100,100};
      PCHAR_INFO pchar;
      COORD bufferSize = {5, 4};
      COORD MyCoord = {5, 4};
      PSMALL_RECT MyRect;
     
      ReadConsoleOutput(hConOut,pchar,bufferSize, MyCoord, MyRect);
      MessageBox(0,LPCSTR(pchar),LPCSTR(pchar),0);
      */
      /*
      TCHAR buffer[4096];
      DWORD rRegion;
      COORD bufferSize = {10, 8};
      COORD bufferCoord = {0, 0};
      ReadConsoleOutputCharacter(hConOut, buffer, 4095,bufferCoord,&rRegion);
      MessageBox(0,LPCSTR(buffer),LPCSTR(buffer),0);
      */
      return;
      }
     
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}

void WriteToConsoleOLD(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);
     
     
      char buf[1024];
      char tmpbuf[128];
      DWORD reDword = 128;
      BOOL res;
      do
      {
         Sleep(1000); //ReadFile takes time..
         res=ReadFile(hConOut,tmpbuf,128,&reDword,0);
         tmpbuf[reDword] = '\0';
         strncat(buf,tmpbuf,reDword);
         //MessageBox(0,LPCSTR(tmpbuf),0,0);
         //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
      }while (reDword == 128);
      //MessageBox(0,buf,0,0);
      SendData(Sock, buf);

      return;
      }
     
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}


int InitSocket(int nPort)
{

   LocalSin.sin_family = AF_INET;
   LocalSin.sin_port = 0;
   
   RemoteSin.sin_family = AF_INET;
   RemoteSin.sin_port = htons(nPort);

   if ((RemoteSin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")) == INADDR_NONE)
      return false;      // Error setting IP

   if ((Sock = socket(PF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
      return false;      // Error creating socket

   if (bind(Sock, (sockaddr *)&LocalSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;      // Error binding socket

   if (connect(Sock, (sockaddr *)&RemoteSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;

   WSAAsyncSelect(Sock, hWnd, WM_USER + 2, FD_READ | FD_CLOSE);

   return TRUE;
}

int SendData(SOCKET sock, char * lpszData)
{
   return send(sock, lpszData, strlen(lpszData), 0);
}

LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   switch (uMsg)
   {
   case WM_DESTROY:
      PostQuitMessage(0);
      break;

   case WM_USER + 2:
      HandleData(wParam, lParam);
      break;
   }

   return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

void CALLBACK HandleWinEvent(HWINEVENTHOOK hook, DWORD event, HWND hwnd,
                             LONG idObject, LONG idChild,
                             DWORD dwEventThread, DWORD dwmsEventTime)
{
        if (event == EVENT_CONSOLE_START_APPLICATION)
        {
            //MessageBox(0,LPCSTR("New Console Application Created"),0,0);
        }
        else if (event == EVENT_CONSOLE_UPDATE_SIMPLE)
        {
         /*
         LOWORD idChild = letter
         HIWORD idChild = http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx
         LOWORD idObject = Colum
         HIWORD idObject =  ROWEVENT_CONSOLE_UPDATE_SIMPLE
         
         WORD a = LOWORD(idObject);       
            WORD b = HIWORD(idObject);         
            WORD c = LOWORD(idChild);   
         WORD d = HIWORD(idChild);
         */
          
            //MessageBox(0,LPCSTR("New Console Simple Update"),0,0);
        }
      else if (event == EVENT_CONSOLE_UPDATE_REGION)
        {
            //MessageBox(0,LPCSTR("New Console Region Update"),0,0);
         HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
          
           DWORD rRegion;
           COORD bufferSize = GetLargestConsoleWindowSize(hConOut);
           //COORD bufferSize = {10, 8};
           COORD bufferCoord = {LOWORD(idObject), HIWORD(idObject)};
           COORD ENDCoord = {LOWORD(idChild), HIWORD(idChild)};

           if (ENDCoord.Y == 299) { ENDCoord.Y = 0; }

           long Distance;
           Distance = (ENDCoord.Y * 80 + ENDCoord.X) - (bufferCoord.Y * 80 + bufferCoord.X) + 1;

           TCHAR buffer[1024];
           ZeroMemory(&buffer,sizeof(buffer));
            
           ReadConsoleOutputCharacter(hConOut, buffer, Distance * sizeof(TCHAR), bufferCoord,&rRegion);
           //ReadConsoleOutputCharacter(hConOut, buffer, sizeof(buffer) * sizeof(TCHAR), bufferCoord,&rRegion);
           //ReadConsoleOutputCharacter(hConOut, buffer, Distance, bufferCoord,&rRegion);
           if (rRegion == 0) { return; }
           /*
           buffer[rRegion] = p + 48;
           p++;
           buffer[rRegion + 1] = '\0';
           */
           buffer[rRegion] = '\0';
           Sleep(50);
           send(Sock, buffer, rRegion + 1, 0);
           //MessageBox(0,LPCSTR(buffer),0,0);
        }
      else if (event == EVENT_CONSOLE_CARET)
        {
            //MessageBox(0,LPCSTR("New Console Caret Update"),0,0);
        }
      else if (event == EVENT_CONSOLE_END_APPLICATION)
        {
            //MessageBox(0,LPCSTR("New Console Application Distroyed"),0,0);
        }
}

int HandleData(WPARAM wParam, LPARAM lParam)
{
   SOCKET sock = (SOCKET)wParam;
   WORD event = LOWORD(lParam);
   WORD error = HIWORD(lParam);

   if (event == FD_CLOSE)
   {
        closesocket(sock);
      PostQuitMessage(0);
   }
   else if (event == FD_READ)
   {
      char szBuffer[1024];
      ZeroMemory(szBuffer, 1024);
      recv(sock, szBuffer, 1024, 0);

      //MessageBox(hWnd, szBuffer, "Received Data!", MB_OK);
     WriteToConsole(szBuffer);

      //closesocket(sock);
   }
   return TRUE;
}   

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

   WSAData wsa;
   WSAStartup(MAKEWORD(1, 1), &wsa);

   WNDCLASS wnd;
   wnd.cbClsExtra = 0;
   wnd.cbWndExtra = 0;
   wnd.hbrBackground = (HBRUSH) COLOR_WINDOW;
   wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
   wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION);
   wnd.hInstance = hInst;
   wnd.lpfnWndProc = WinProc;
   wnd.lpszClassName = "GenericClientClass";
   wnd.lpszMenuName = NULL;
   wnd.style = CS_HREDRAW | CS_VREDRAW;

   RegisterClass(&wnd);

   hWnd = CreateWindow("GenericClientClass", "Connecting to port 6666...", WS_CAPTION | WS_POPUPWINDOW, 0, 100, 200, 100, NULL, NULL, hInst, NULL);

   if (!hWnd)
     return -2;

   ShowWindow(hWnd, SW_SHOWNORMAL);

   if (!InitSocket(6666))
   {
     char szBuffer[1024];
 
     sprintf(szBuffer, "Error connecting [%d]", WSAGetLastError());

     MessageBox(hWnd, szBuffer, "Error", MB_OK);
 
     DestroyWindow(hWnd);
   }

   AllocConsole();

   DWORD hwdehk;

    hwdehk = SetWinEventHook(EVENT_CONSOLE_START_APPLICATION,EVENT_CONSOLE_START_APPLICATION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
    hwdehk = SetWinEventHook(EVENT_CONSOLE_UPDATE_SIMPLE,EVENT_CONSOLE_UPDATE_SIMPLE, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
    hwdehk = SetWinEventHook(EVENT_CONSOLE_UPDATE_REGION,EVENT_CONSOLE_UPDATE_REGION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   hwdehk = SetWinEventHook(EVENT_CONSOLE_CARET,EVENT_CONSOLE_CARET, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   hwdehk = SetWinEventHook(EVENT_CONSOLE_END_APPLICATION,EVENT_CONSOLE_END_APPLICATION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   CreateThread(NULL, 0, CreateConsole, (LPDWORD)0, 0, 0);

   MSG msg;

   while (GetMessage(&msg, NULL, 0, 0))
   {
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }

   UnhookWinEvent(hwdehk);
   hwdehk=0;
   WSACleanup();

   return msg.wParam;
}

void old(void) {

/*
local_info.sin_family = AF_INET;
      local_info.sin_port = htons(cc_port);
      local_info.sin_addr.s_addr = htons(INADDR_ANY);
     
      std::cout << "attempting to bind... ";
      if(bind(sock, (SOCKADDR*) &local_info, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to prepare socket for listening... ";
      if(listen(sock, 5) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to listen for a connection";
      do
      {
            tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
            std::cout << "!";
      }
      while(tmp_sock == SOCKET_ERROR);
      std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

      closesocket(sock);
      closesocket(tmp_sock);

  */


   //AllocConsole();
   //HWND hwnd = GetConsoleWindow();
   //if (hwnd)
   {
      //console.Attach(hwnd);
      //console.ShowWindow(SW_HIDE);
   }
}
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am

FINAL

Postby Admin » Wed Dec 03, 2008 7:23 am

Code: Select all
'Courier New font for textbox 2 width = 8535 height is 2655
Dim SecondTime As Boolean

Private Sub Form_Load()
Winsock1.LocalPort = 6666
Winsock1.Listen
End Sub

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
    Winsock1.SendData Text1.Text
    Text1.Text = ""
End If
End Sub

Private Sub Winsock1_Close()
Winsock1.Close
Winsock1.Listen
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
Winsock1.Close
Winsock1.Accept requestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData Data, vbString
Debug.Print Data
Text2.Text = Text2.Text & Data
Text2.SelStart = Len(Text2.Text)
End Sub

Private Sub Text2_Change()
If SecondTime Then Exit Sub
If InStr(Text2.Text, " ") Then
SecondTime = True
Text2.Text = Replace(Text2.Text, " ", Chr$(160))
SecondTime = False
End If
End Sub


Code: Select all
// Server.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <tchar.h>
#include <string.h>
#include <stdio.h>
#include <winsock.h>
#include <iostream>
#include <winable.h> //SetWinHook?
#include <sstream> //DbgOutInt
#include "CrtDbg.h" //Debug
using namespace std;
#pragma comment( lib, "wsock32.lib" )

#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 25
//http://msdn.microsoft.com/en-us/library/ms971319.aspx
#define  EVENT_CONSOLE_CARET            0x4001
#define  EVENT_CONSOLE_UPDATE_REGION      0x4002
#define  EVENT_CONSOLE_UPDATE_SIMPLE      0x4003
#define  EVENT_CONSOLE_UPDATE_SCROLL      0x4004
#define  EVENT_CONSOLE_LAYOUT            0x4005
#define  EVENT_CONSOLE_START_APPLICATION      0x4006
#define  EVENT_CONSOLE_END_APPLICATION      0x4007

int InitSocket(int nPort);
int SendData(SOCKET sock, char * lpszData);
LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int HandleData(WPARAM wParam, LPARAM lParam);
int HandleAccept(WPARAM wParam, LPARAM lParam);

   sockaddr_in LocalSin;
   sockaddr_in RemoteSin;
   SOCKET      Sock;
   HWND      hWnd;
   HINSTANCE   hInst;
   HANDLE      rPipe;
   HANDLE      wPipe;
   int         Column=0;

STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
DWORD WINAPI CreateConsole(LPVOID lp)
{

   SECURITY_ATTRIBUTES secattr;
   ZeroMemory(&secattr,sizeof(secattr));
   secattr.nLength = sizeof(secattr);
   secattr.bInheritHandle = TRUE;

   //Create pipes to write and read data
   CreatePipe(&rPipe,&wPipe,&secattr,0);
   //
   
   ZeroMemory(&sInfo,sizeof(sInfo));
   
   ZeroMemory(&pInfo,sizeof(pInfo));
   sInfo.cb=sizeof(sInfo);
   //sInfo.dwFlags=STARTF_USESTDHANDLES;
   //sInfo.hStdInput=NULL;
   //sInfo.hStdOutput=wPipe;
   //sInfo.hStdError=wPipe;
   //CreateProcess(0, "cmd.exe",0,0,TRUE,NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
   CreateProcess(0, "cmd.exe",0,0,TRUE,0,0,0,&sInfo,&pInfo);
   //CloseHandle(wPipe);

   return 0;
   char buf[1024];
   char tmpbuf[128];
     DWORD reDword = 128;
     BOOL res;
     do
     {
      Sleep(1000); //ReadFile takes time..
      res=ReadFile(rPipe,tmpbuf,128,&reDword,0);
      tmpbuf[reDword] = '\0';
      strncat(buf,tmpbuf,reDword);
      //MessageBox(0,LPCSTR(tmpbuf),0,0);
        //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
     }while (reDword == 128);
   //MessageBox(0,buf,0,0);
   SendData(Sock, buf);
   return 0;
}

void WriteToConsole(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);

     /*
      Sleep(1000);
      //CONSOLE_SCREEN_BUFFER_INFO bInfo;
      //CHAR_INFO buffer[30];
     
      char buf[1024];
      char tmpbuf[128];
     DWORD reDword = 128;
     BOOL res;
     do
     {
      Sleep(1000); //ReadFile takes time..
      res=ReadFile(hConOut,tmpbuf,128,&reDword,0);
      tmpbuf[reDword] = '\0';
      strncat(buf,tmpbuf,reDword);
      //MessageBox(0,LPCSTR(tmpbuf),0,0);
        //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
     }while (reDword == 128);
   MessageBox(0,buf,0,0);
      */
      /*
      SMALL_RECT readRegion = {0,0,100,100};
      PCHAR_INFO pchar;
      COORD bufferSize = {5, 4};
      COORD MyCoord = {5, 4};
      PSMALL_RECT MyRect;
     
      ReadConsoleOutput(hConOut,pchar,bufferSize, MyCoord, MyRect);
      MessageBox(0,LPCSTR(pchar),LPCSTR(pchar),0);
      */
      /*
      TCHAR buffer[4096];
      DWORD rRegion;
      COORD bufferSize = {10, 8};
      COORD bufferCoord = {0, 0};
      ReadConsoleOutputCharacter(hConOut, buffer, 4095,bufferCoord,&rRegion);
      MessageBox(0,LPCSTR(buffer),LPCSTR(buffer),0);
      */
      return;
      }
     
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}

void WriteToConsoleOLD(char StringToWrite[])
{
   HANDLE hConIn = CreateFile(LPCSTR("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   INPUT_RECORD ir[2];

   for (int i=0; i < 50; i++) {
      if (StringToWrite[i] == '\0') {
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = '\r';
      WriteConsoleInput (hConIn, ir, 2, 0);
     
     
      char buf[1024];
      char tmpbuf[128];
      DWORD reDword = 128;
      BOOL res;
      do
      {
         Sleep(1000); //ReadFile takes time..
         res=ReadFile(hConOut,tmpbuf,128,&reDword,0);
         tmpbuf[reDword] = '\0';
         strncat(buf,tmpbuf,reDword);
         //MessageBox(0,LPCSTR(tmpbuf),0,0);
         //strcat(buf,LPCSTR(tmpbuf));//csTemp.Left(reDword);
      }while (reDword == 128);
      //MessageBox(0,buf,0,0);
      SendData(Sock, buf);

      return;
      }
     
      ir[0].EventType = KEY_EVENT;
      ir[0].Event.KeyEvent.bKeyDown = TRUE;
      ir[0].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      ir[1].EventType = KEY_EVENT;
      ir[1].Event.KeyEvent.bKeyDown = FALSE;
      ir[1].Event.KeyEvent.uChar.UnicodeChar = StringToWrite[i];
      WriteConsoleInput (hConIn, ir, 2, 0);
   }
}


int InitSocket(int nPort)
{

   LocalSin.sin_family = AF_INET;
   LocalSin.sin_port = 0;
   
   RemoteSin.sin_family = AF_INET;
   RemoteSin.sin_port = htons(nPort);

   if ((RemoteSin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")) == INADDR_NONE)
      return false;      // Error setting IP

   if ((Sock = socket(PF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
      return false;      // Error creating socket

   if (bind(Sock, (sockaddr *)&LocalSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;      // Error binding socket

   if (connect(Sock, (sockaddr *)&RemoteSin, sizeof(sockaddr_in)) == SOCKET_ERROR)
      return false;

   WSAAsyncSelect(Sock, hWnd, WM_USER + 2, FD_READ | FD_CLOSE);

   return TRUE;
}

int SendData(SOCKET sock, char * lpszData)
{
   return send(sock, lpszData, strlen(lpszData), 0);
}

LRESULT WINAPI WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   switch (uMsg)
   {
   case WM_DESTROY:
      PostQuitMessage(0);
      break;

   case WM_USER + 2:
      HandleData(wParam, lParam);
      break;
   }

   return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

void CALLBACK HandleWinEvent(HWINEVENTHOOK hook, DWORD event, HWND hwnd,
                             LONG idObject, LONG idChild,
                             DWORD dwEventThread, DWORD dwmsEventTime)
{
        if (event == EVENT_CONSOLE_START_APPLICATION)
        {
            //MessageBox(0,LPCSTR("New Console Application Created"),0,0);
        }
        else if (event == EVENT_CONSOLE_UPDATE_SIMPLE)
        {
         /*
         LOWORD idChild = letter
         HIWORD idChild = http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx
         LOWORD idObject = Colum
         HIWORD idObject =  ROWEVENT_CONSOLE_UPDATE_SIMPLE
         
         WORD a = LOWORD(idObject);       
            WORD b = HIWORD(idObject);         
            WORD c = LOWORD(idChild);   
         WORD d = HIWORD(idChild);
         */
           
            //MessageBox(0,LPCSTR("New Console Simple Update"),0,0);
        }
      else if (event == EVENT_CONSOLE_UPDATE_REGION)
        {
            //MessageBox(0,LPCSTR("New Console Region Update"),0,0);
         HANDLE hConOut =  CreateFile(LPCSTR("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
           
           DWORD rRegion;
           COORD bufferSize = GetLargestConsoleWindowSize(hConOut);
           COORD bufferCoord = {LOWORD(idObject), HIWORD(idObject)};
           COORD ENDCoord = {LOWORD(idChild), HIWORD(idChild)};

           if (ENDCoord.Y == 299) { ENDCoord.Y = 0; }

           long Distance;
           Distance = (ENDCoord.Y * 80 + ENDCoord.X) - (bufferCoord.Y * 80 + bufferCoord.X) + 1;

           TCHAR buffer[1024];
           ZeroMemory(&buffer,sizeof(buffer));
           
           ReadConsoleOutputCharacter(hConOut, buffer, Distance * sizeof(TCHAR), bufferCoord,&rRegion);

           if (rRegion == 0) { return; }
         if (bufferCoord.Y > Column) { send(Sock, "\r\n", 2, 0); Column = bufferCoord.Y; }
           send(Sock, buffer, rRegion, 0);

        }
      else if (event == EVENT_CONSOLE_CARET)
        {
            //MessageBox(0,LPCSTR("New Console Caret Update"),0,0);
        }
      else if (event == EVENT_CONSOLE_END_APPLICATION)
        {
            //MessageBox(0,LPCSTR("New Console Application Distroyed"),0,0);
        }
}

int HandleData(WPARAM wParam, LPARAM lParam)
{
   SOCKET sock = (SOCKET)wParam;
   WORD event = LOWORD(lParam);
   WORD error = HIWORD(lParam);

   if (event == FD_CLOSE)
   {
        closesocket(sock);
      PostQuitMessage(0);
   }
   else if (event == FD_READ)
   {
      char szBuffer[1024];
      ZeroMemory(szBuffer, 1024);
      recv(sock, szBuffer, 1024, 0);

      //MessageBox(hWnd, szBuffer, "Received Data!", MB_OK);
     WriteToConsole(szBuffer);

      //closesocket(sock);
   }
   return TRUE;
}   

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

   WSAData wsa;
   WSAStartup(MAKEWORD(1, 1), &wsa);

   WNDCLASS wnd;
   wnd.cbClsExtra = 0;
   wnd.cbWndExtra = 0;
   wnd.hbrBackground = (HBRUSH) COLOR_WINDOW;
   wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
   wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION);
   wnd.hInstance = hInst;
   wnd.lpfnWndProc = WinProc;
   wnd.lpszClassName = "GenericClientClass";
   wnd.lpszMenuName = NULL;
   wnd.style = CS_HREDRAW | CS_VREDRAW;

   RegisterClass(&wnd);

   hWnd = CreateWindow("GenericClientClass", "Connecting to port 6666...", WS_CAPTION | WS_POPUPWINDOW, 0, 100, 200, 100, NULL, NULL, hInst, NULL);

   if (!hWnd)
     return -2;

   ShowWindow(hWnd, SW_SHOWNORMAL);

   if (!InitSocket(6666))
   {
     char szBuffer[1024];
 
     sprintf(szBuffer, "Error connecting [%d]", WSAGetLastError());

     MessageBox(hWnd, szBuffer, "Error", MB_OK);
 
     DestroyWindow(hWnd);
   }

   AllocConsole();

   DWORD hwdehk;

    hwdehk = SetWinEventHook(EVENT_CONSOLE_START_APPLICATION,EVENT_CONSOLE_START_APPLICATION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
    hwdehk = SetWinEventHook(EVENT_CONSOLE_UPDATE_SIMPLE,EVENT_CONSOLE_UPDATE_SIMPLE, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
    hwdehk = SetWinEventHook(EVENT_CONSOLE_UPDATE_REGION,EVENT_CONSOLE_UPDATE_REGION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   hwdehk = SetWinEventHook(EVENT_CONSOLE_CARET,EVENT_CONSOLE_CARET, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   hwdehk = SetWinEventHook(EVENT_CONSOLE_END_APPLICATION,EVENT_CONSOLE_END_APPLICATION, NULL ,&HandleWinEvent, 0, 0, WINEVENT_SKIPOWNPROCESS | WINEVENT_OUTOFCONTEXT);
   CreateThread(NULL, 0, CreateConsole, (LPDWORD)0, 0, 0);

   MSG msg;

   while (GetMessage(&msg, NULL, 0, 0))
   {
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }

   UnhookWinEvent(hwdehk);
   hwdehk=0;
   WSACleanup();

   return msg.wParam;
}

void old(void) {

/*
local_info.sin_family = AF_INET;
      local_info.sin_port = htons(cc_port);
      local_info.sin_addr.s_addr = htons(INADDR_ANY);
     
      std::cout << "attempting to bind... ";
      if(bind(sock, (SOCKADDR*) &local_info, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to prepare socket for listening... ";
      if(listen(sock, 5) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to listen for a connection";
      do
      {
            tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
            std::cout << "!";
      }
      while(tmp_sock == SOCKET_ERROR);
      std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

      closesocket(sock);
      closesocket(tmp_sock);

  */


   //AllocConsole();
   //HWND hwnd = GetConsoleWindow();
   //if (hwnd)
   {
      //console.Attach(hwnd);
      //console.ShowWindow(SW_HIDE);
   }
}
Admin
Site Admin
 
Posts: 924
Joined: Thu Aug 23, 2007 10:35 am


Return to IO

Who is online

Users browsing this forum: No registered users and 1 guest

cron