Page 1 of 1

ProgramLib (read program output, etc)

Posted: Thu Jan 31, 2008 6:38 pm
by Inf0Byt3
Just a small code made from what I found on the forum. It's purpose is to offer an alternative to the PB command set (even if it's not that good like PB's one). I worked with this because ReadProgramError() doesn't work with Unicode for now so I needed a fast solution.

Code: Select all

;ProgramLib
;31 Jan 2008, works with PB >= 4, Win >= 98
;Original code by spangly
;Tweaks by DoubleDutch
;Small additions by Inf0Byt3

Global PINFO.PROCESS_INFORMATION
Global hWritePipe.l,hReadPipe.l
Global compx.l,last.s,PID.l

Global *PipeMem = AllocateMemory(1024)

Procedure.s ReadProgramOutput()
 BytesRead.l = 0
 r.l=PeekNamedPipe_(hreadPipe,0,0,0,@BytesRead,0)
 If BytesRead>0
  o.l=ReadFile_(hReadPipe,*PipeMem,1023,@BytesRead,0)
  If o
   Ret.s = PeekS(*PipeMem,BytesRead,#PB_UTF8)
   RtlZeroMemory_(*PipeMem,1024)
   ProcedureReturn Ret
  EndIf
 EndIf
EndProcedure

Procedure.l RunProgramEx(cmd.s) 
  SECA.SECURITY_ATTRIBUTES
  SECA\nLength=SizeOf(SECURITY_ATTRIBUTES)
  SECA\bInheritHandle=1
  SECA\lpSecurityDescriptor=0
  xx.l=CreatePipe_(@hReadPipe,@hWritePipe,@SECA,1)
  SINFO.STARTUPINFO
  SINFO\cb=SizeOf(STARTUPINFO)
  SINFO\dwFlags=#STARTF_USESTDHANDLES|#STARTF_USESHOWWINDOW
  SINFO\hStdOutput=hWritePipe
  SINFO\hStdError=hWritePipe
  ResultC = CreateProcess_(0,cmd,@SECA,@SECA,1,#CREATE_NEW_CONSOLE,0,0,@SINFO,@PINFO)
  PID = PINFO\dwProcessId
  ProcedureReturn ResultC
EndProcedure

Procedure.l ProgramRunningEx()
 GetExitCodeProcess_(PINFO\hProcess,@exitcode)
 If ExitCode=259
  ProcedureReturn 1
 Else
  ProcedureReturn 0
 EndIf
EndProcedure

Procedure.l KillProgramEx()
 phandle = OpenProcess_(#PROCESS_TERMINATE, #False, pid)
 If phandle <> #Null
  If TerminateProcess_(phandle, 1)
   result = #True
  EndIf
  CloseHandle_(phandle)
 EndIf
 ProcedureReturn result 
EndProcedure

Procedure.l CloseProgramEx()
 CloseHandle_(PINFO\hProcess)
 CloseHandle_(PINFO\hThread)
 CloseHandle_(hReadPipe) 
 ProcedureReturn 1
EndProcedure

OpenConsole()
If RunProgramEx("cmd /?")
 While ProgramRunningEx()
  Returns.s = ReadProgramOutput()
  if Returns <> ""
   PrintN(Returns)
  endif
 Wend
 CloseProgramEx()
 KillProgramEx()
Else
 Debug GetLastError_()
EndIf
Input()
I can add a cache at request, e.g. manage multiple programs at the same time, close one, run another, just like PB does (Runprogram(0,"myprogram")).

Posted: Thu Jan 31, 2008 9:53 pm
by SFSxOI
Global hWritePipe.l,hReadPipe.lGlobal compx.l,last.s,PID.l ???

keep getting 'Structure not found lGlobal"

something else go with this?

Posted: Thu Jan 31, 2008 9:57 pm
by srod
You have 2 lines merged together. Put a carriage return just before the second global.

Posted: Thu Jan 31, 2008 10:41 pm
by Inf0Byt3
Oopsie! Fixing...