WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

DOS Console UDFs

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Write Data to An Existing Console Window STDOUT


;Writes Text to an Existing Console (STDOUT)
;Requires Windows XP or newer.


#DefineFunction udfGetWindowThreadProcessId(hwnd)
	hker = DllLoad("user32.DLL")
	buf = BinaryAlloc(4)
	ret = DLLCall(hker, long:"GetWindowThreadProcessId", long:hwnd, lpbinary:buf)
	consoleid = BinaryPeek4(buf,0)
	BinaryFree(buf)
	DllFree(hker)
	Return consoleid
#EndFunction

#DefineFunction udfGetConsoleProcessID()
	wnd = FindWindow('ConsoleWindowClass');
	if wnd <> "" Then
		hwnd = DllHwnd(wnd)
		result = udfGetWindowThreadProcessId(hwnd )
		return result
	endif
	return 0
#EndFunction

#DefineFunction udfAttachConsole(consoleId)
	hker = DllLoad("KERNEL32.DLL")
	DLLCall(hker, long:"AttachConsole", LONG:consoleId)
	DllFree(hker)
	return 1
#EndFunction

#DefineFunction udfGetStdHandle()
	hker = DllLoad("KERNEL32.DLL")
	ret = DLLCall(hker, long:"GetStdHandle", long:-11)
	DllFree(hker)
	return ret
#EndFunction


#DefineFunction udfWriteConsole(hStdOutput,data)
	hker = DllLoad("KERNEL32.DLL")
	linebuff = binaryalloc(strlen(data))
	mret = BinaryAlloc(4)
	binarypokestr(linebuff, 0, data)
	DLLCall(hker, long:"WriteConsoleA", long:hStdOutput, lpbinary:linebuff, long:strlen(data), lpbinary:mret, lpnull)
	BinaryFree(linebuff)
	BinaryFree(mret)
	DllFree(hker)
	return 1
#EndFunction

#DefineFunction udfFreeConsole()
	hker = DllLoad("KERNEL32.DLL")
	DLLCall(hker, long:"FreeConsole")
	DllFree(hker)
	return 1
#EndFunction


;Check if running on XP or newer
if StrReplace(WinVersion(5),'-','') < "251" then exit



consoleid = udfGetConsoleProcessID()
if consoleid == 0
	 Message("Error","No existing console window")
	 exit
endif

udfAttachConsole(consoleId)

hStdOutput = udfGetStdHandle()

for i = 1 to 200
	line = strcat("Hello there ", i, @CRLF)
	udfWriteConsole(hStdOutput,line)
next

Message("STDOUT: WRITE", "COMPLETE")

udfFreeConsole()

Exit

Article ID:   W16737
File Created: 2017:12:16:16:05:46
Last Updated: 2017:12:16:16:05:46