Page 1 of 1

Send String to Console

Posted: Fri Apr 02, 2010 11:51 pm
by Nituvious
Hi all, a little while ago I needed a way to send a string of text to a console window on Windows. I failed miserably at it.
But, after coming across the old project I decided to give it another shot and it turned out great(Yay for the Survival Guide and Kale's Guide!) for my own use. Maybe someone could benefit from this. :wink: I figure since I'm always asking for help here I could *try* and contribute! :)
It probably doesn't look pretty, but it works. :)

Code: Select all

Global hInput

Procedure SendConsole(szText.s)
  szLength = Len(szText.s)
  For sz = 0 To szLength+1
    szCharacter$ = Mid(szText.s,sz+1,1)
    szLetterByLetter=Asc(szCharacter$)
    PostMessage_(hInput,#WM_CHAR,szLetterByLetter,0)
  Next
  PostMessage_(hInput,#WM_CHAR,13,0)
EndProcedure

hInput = FindWindow_(0,"Administrator: c:\Windows\system32\cmd.exe")
If hInput = 0
  Debug "Error, command prompt not open or string mismatch!"
Else
  SendConsole("echo Hello world!! This is a string, I think? What about numbers? 1+1=393")
EndIf

Re: Send String to Console

Posted: Sat Apr 03, 2010 2:15 am
by SFSxOI
Some of the best working things in the world are ugly, and some of the worst working things in the world are very pretty. I would not worry about it. This is simple, short, and to the point, I like it. Thank you for posting your creation. :)

Re: Send String to Console

Posted: Sat Apr 03, 2010 7:09 am
by Pureabc
Very nice trick, thanks for sharing.

Anyone knows an easy way to put a "cmd.exe window" inside a regular window?

Re: Send String to Console

Posted: Tue Apr 06, 2010 12:57 am
by idle
good tip, never thought about doing that!

Re: Send String to Console

Posted: Tue Apr 06, 2010 4:48 am
by Nituvious
Thanks to Idle for improving on the code! :)

Code: Select all

Global hInput,wintitle.s
Procedure EnumWindProc(hwnd,*lpstring)
  stitle.s = Space(256)
  GetWindowText_(hwnd,@stitle,256)  
  str$ = PeekS(*lpstring) 
  If FindString(stitle,str$,1)
    ShowWindow_(hwnd,1)
    wintitle = stitle 
    hinput = hwnd 
    ProcedureReturn 0
  Else 
    ProcedureReturn 1
  EndIf   
EndProcedure   

Procedure SendConsole(szText.s)
  
  If Not wintitle  
    EnumWindows_(@EnumWindProc(),@"cmd.exe")
  Else 
    hinput = FindWindow_(0,wintitle)
  EndIf   
  
  If Not hinput 
    RunProgram("cmd.exe")
    delay(200)
    EnumWindows_(@EnumWindProc(),@"cmd.exe") 
  EndIf 
  
  If hinput   
     szLength = Len(szText.s)
     For sz = 0 To szLength+1
       szCharacter$ = Mid(szText.s,sz+1,1)
       szLetterByLetter=Asc(szCharacter$)
       PostMessage_(hInput,#WM_CHAR,szLetterByLetter,0)
     Next
     PostMessage_(hInput,#WM_CHAR,13,0)
  EndIf 
     
EndProcedure


SendConsole("echo Hello world!! This is a string, I think? What about numbers? 1+1=393")