Author Topic: VB6 Console Applications  (Read 6923 times)

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
VB6 Console Applications
« on: October 22, 2015, 11:41:59 PM »
I would like to use VB6 to create non-GUI console applications and it seems this is easy to do. My main goal with this thread is accessing COM/OLE functionality in a console application which could be used in a batch file or task scheduler. I stumbled onto an example of how to create a VB6 console application and a utility to change the mode of the .exe program. (GUI or Console) I'm not sure if it will work with non-VB6 programs but I'll give it a try by making a Script BASIC standalone console script into a headless Windows applications.



Code: Visual Basic
  1. Attribute VB_Name = "Module1"
  2. Option Explicit
  3.  
  4. 'Console Application Sample
  5. 'Written by Nir Sofer.
  6. '
  7. 'Web site: http://nirsoft.mirrorz.com
  8. '
  9. 'In order to create a console application from this code, follow the instructions below:
  10. '1. Make an executable file from this project.
  11. '2. Run the "Application Mode Changer" utility and change the mode of the
  12. 'executable file to "Console Application".
  13.  
  14. Public Declare Function GetStdHandle Lib "kernel32" _
  15. (ByVal nStdHandle As Long) As Long
  16.  
  17. Private Declare Function WriteFile Lib "kernel32" _
  18. (ByVal hFile As Long, _
  19. lpBuffer As Any, _
  20. ByVal nNumberOfBytesToWrite As Long, _
  21. lpNumberOfBytesWritten As Long, _
  22. lpOverlapped As Any) As Long
  23.  
  24. Public Const STD_OUTPUT_HANDLE = -11&
  25.  
  26. Private Type COORD
  27.         x As Integer
  28.         y As Integer
  29. End Type
  30.  
  31. Private Type SMALL_RECT
  32.         Left As Integer
  33.         Top As Integer
  34.         Right As Integer
  35.         Bottom As Integer
  36. End Type
  37.  
  38. Private Type CONSOLE_SCREEN_BUFFER_INFO
  39.         dwSize As COORD
  40.         dwCursorPosition As COORD
  41.         wAttributes As Integer
  42.         srWindow As SMALL_RECT
  43.         dwMaximumWindowSize As COORD
  44. End Type
  45. Private Declare Function GetConsoleScreenBufferInfo Lib "kernel32" _
  46. (ByVal hConsoleOutput As Long, _
  47. lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Long
  48.  
  49. Private Declare Function SetConsoleTextAttribute Lib "kernel32" _
  50. (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
  51.  
  52. Private Const FOREGROUND_BLUE = &H1     '  text color contains blue.
  53. Private Const FOREGROUND_GREEN = &H2     '  text color contains green.
  54. Private Const FOREGROUND_INTENSITY = &H8     '  text color is intensified.
  55. Private Const FOREGROUND_RED = &H4     '  text color contains red.
  56.  
  57. Private hOutput             As Long
  58.  
  59. 'The following function writes the content of sText variable into the console window:
  60. Private Function WriteToConsole(sText As String) As Boolean
  61.     Dim lWritten            As Long
  62.    
  63.     If WriteFile(hOutput, ByVal sText, Len(sText), lWritten, ByVal 0) = 0 Then
  64.         WriteToConsole = False
  65.     Else
  66.         WriteToConsole = True
  67.     End If
  68. End Function
  69.  
  70. Public Sub Main()
  71.     Dim scrbuf      As CONSOLE_SCREEN_BUFFER_INFO
  72.    
  73.     'Get the standard output handle
  74.    hOutput = GetStdHandle(STD_OUTPUT_HANDLE)
  75.     GetConsoleScreenBufferInfo hOutput, scrbuf
  76.     WriteToConsole "Console Application Example In Visual Basic." & vbCrLf
  77.     WriteToConsole "Written by Nir Sofer" & vbCrLf
  78.     WriteToConsole "Web site: http://nirsoft.mirrorz.com" & vbCrLf & vbCrLf
  79.    
  80.     'Change the text color to blue
  81.    SetConsoleTextAttribute hOutput, FOREGROUND_BLUE Or FOREGROUND_INTENSITY
  82.     WriteToConsole "Blue Color !!" & vbCrLf
  83.    
  84.     'Change the text color to yellow
  85.    SetConsoleTextAttribute hOutput, FOREGROUND_RED Or FOREGROUND_GREEN Or FOREGROUND_INTENSITY
  86.     WriteToConsole "Yellow Color !!" & vbCrLf
  87.    
  88.     'Restore the previous text attributes.
  89.    SetConsoleTextAttribute hOutput, scrbuf.wAttributes
  90.     If Len(Command$) <> 0 Then
  91.         'Show the command line parameters:
  92.        WriteToConsole vbCrLf & "Command Line Parameters: " & Command$ & vbCrLf
  93.     End If
  94. End Sub
  95.  

Project Web Site

Microsoft reference for a VB6 Console

Zip contains all source and executables for Windows 32 bit.
« Last Edit: October 23, 2015, 12:59:33 AM by John »

Offline Mike Lobanovsky

  • ON-HOLD
  • BASIC Developer
  • Posts: 261
Re: VB6 Console Applications
« Reply #1 on: October 23, 2015, 07:49:32 PM »
Here is a more profound solution to this problem. It enables you to create an entire VB6 template project usable for easy creation of console VB6 apps with both output and input. ("the brick" in the text in fact means "a VB6 building block")

This is a Google translation of the Russian original yet it seems quite understandable technically. At the bottom of the page there are also hints on how to create a copy of VB6 IDE that wouldn't crash when interactively debugging (pausing etc.) such apps that are totally "alien" to the windowed-only VB6.
Mike
____________________________________________________________________
(3.6GHz Intel Core i5, 16GB RAM / nVidia GTX 1060Ti , 6GB VRAM / x64 Win7 Ult.)

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #2 on: October 23, 2015, 07:58:29 PM »
You're the man!

Thanks for putting some meaning into this project.

Offline Mike Lobanovsky

  • ON-HOLD
  • BASIC Developer
  • Posts: 261
Re: VB6 Console Applications
« Reply #3 on: October 23, 2015, 08:05:49 PM »
Glad you liked it. I've had such a setup for quite some time now matching my original VB6 and I've never had any problems with it, always creating console-mode VB6 samples for benchmark/comparison purposes if they don't explicitly need any GUI interaction.
Mike
____________________________________________________________________
(3.6GHz Intel Core i5, 16GB RAM / nVidia GTX 1060Ti , 6GB VRAM / x64 Win7 Ult.)

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #4 on: October 23, 2015, 08:29:12 PM »
Attached is my best attempt to capture the content into a stable non-flashing PDF. I was unable to get the examples or template files. Not much here.  :'(

Code: Visual Basic
  1. Attribute VB_Name = "EasyConsole"
  2. ' ******************************************************************************
  3. ' *     Fire-Lines © 2013                                                      *
  4. ' *     Модуль:                                                                *
  5. ' *         EasyConsole                                                        *
  6. ' *     Описание:                                                              *
  7. ' *         Этот модуль вносит революционно простую поддержку написания кон-   *
  8. ' *         сольных приложений на VB.                                          *
  9. ' *     Автор:                                                                 *
  10. ' *         Владислав Петровский (firehacker)                                  *
  11. ' *     История изменений:                                                     *
  12. ' *         *   2013-01-19  firehacker  Файл создан.                           *
  13. ' *                                                                            *
  14. ' *     Текущая версия: 1.0.0                                                  *
  15. ' *                                                                            *
  16. ' ******************************************************************************
  17. Option Explicit
  18.  
  19. Public stdin    As ITextStream
  20. Public stdout   As ITextStream
  21. Public stderr   As ITextStream
  22.  
  23. Public Sub EasyconInitialize(Optional ByVal bUnicodeFormat As Boolean = False)
  24.     Dim fso As IFileSystem3
  25.    
  26.     Set fso = New FileSystemObject
  27.    
  28.     Set stdin = fso.GetStandardStream(0, bUnicodeFormat)
  29.     Set stdout = fso.GetStandardStream(1, bUnicodeFormat)
  30.     Set stderr = fso.GetStandardStream(2, bUnicodeFormat)
  31. End Sub
  32.  
  33. Public Sub EasyconDeinitialize()
  34.     Set stdin = Nothing
  35.     Set stdout = Nothing
  36.     Set stderr = Nothing
  37. End Sub
  38.  
« Last Edit: October 23, 2015, 11:31:34 PM by John »

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #5 on: October 24, 2015, 01:42:06 PM »
I found a good article to help get you going with VB6 console applications.

Actually I would like this to use the same console window I started the program in. Like a true console application.

Quote
Key Statement: So, start a new Standard EXE project and remove the default form (Form1) from the project. Add a module and you're set. That one module is the only component that is needed in a console project, just like a windowless project.

Code: Visual Basic
  1. '+================================================
  2. ' File: Console.bas
  3. '
  4. ' Summary: Demonstrates how it is possible to
  5. ' create and manipulate a console box in Visual
  6. ' Basic.
  7. '
  8. ' Classes: None
  9. '
  10. ' Functions: Main, ConsolePrint, ConsoleRead
  11. '
  12. ' Origin: Visual Basic 6.0 For Windows
  13. '
  14. '------------------------------------------------------
  15. ' (C) Copyright 1999 by Scott Lloyd. All Rights
  16. ' Reserved.
  17. ' Scott Lloyd
  18. '=====================================================+
  19.  
  20. Option Explicit
  21. '''''D E C L A R A T I O N S'''''''''''''''''''''''''''
  22.  
  23. Private Declare Function AllocConsole Lib "kernel32" _
  24.     () As Long
  25.  
  26. Private Declare Function FreeConsole Lib "kernel32" _
  27.     () As Long
  28.  
  29. Private Declare Function GetStdHandle Lib "kernel32" _
  30. (ByVal nStdHandle As Long) As Long
  31.  
  32. Private Declare Function ReadConsole Lib "kernel32" _
  33.     Alias "ReadConsoleA" (ByVal hConsoleInput As Long, _
  34.     ByVal lpBuffer As String, ByVal nNumberOfCharsToRead _
  35.     As Long, _
  36. lpNumberOfCharsRead As Long, lpReserved As Any) As Long
  37.  
  38. Private Declare Function SetConsoleMode Lib "kernel32" (ByVal _
  39. hConsoleOutput As Long, dwMode As Long) As Long
  40.  
  41. Private Declare Function SetConsoleTextAttribute Lib _
  42. "kernel32" (ByVal hConsoleOutput As Long, ByVal _
  43. wAttributes As Long) As Long
  44.  
  45. Private Declare Function SetConsoleTitle Lib "kernel32" Alias _
  46. "SetConsoleTitleA" (ByVal lpConsoleTitle As String) As Long
  47.  
  48. Private Declare Function WriteConsole Lib "kernel32" Alias _
  49. "WriteConsoleA" (ByVal hConsoleOutput As Long, _
  50. ByVal lpBuffer As Any, ByVal nNumberOfCharsToWrite As Long, _
  51. lpNumberOfCharsWritten As Long, lpReserved As Any) As Long
  52.  
  53. ''''C O N S T A N T S'''''''''''''''''''''''''''''''''''''
  54. 'I/O handlers for the console window. These are much like
  55. 'the hWnd handlers to form windows.
  56.  
  57. Private Const STD_INPUT_HANDLE = -10&
  58. Private Const STD_OUTPUT_HANDLE = -11&
  59. Private Const STD_ERROR_HANDLE = -12&
  60.  
  61. 'Color values for SetConsoleTextAttribute.
  62. Private Const FOREGROUND_BLUE = &H1
  63. Private Const FOREGROUND_GREEN = &H2
  64. Private Const FOREGROUND_RED = &H4
  65. Private Const FOREGROUND_INTENSITY = &H8
  66. Private Const BACKGROUND_BLUE = &H10
  67. Private Const BACKGROUND_GREEN = &H20
  68. Private Const BACKGROUND_RED = &H40
  69. Private Const BACKGROUND_INTENSITY = &H80
  70.  
  71. 'For SetConsoleMode (input)
  72. Private Const ENABLE_LINE_INPUT = &H2
  73. Private Const ENABLE_ECHO_INPUT = &H4
  74. Private Const ENABLE_MOUSE_INPUT = &H10
  75. Private Const ENABLE_PROCESSED_INPUT = &H1
  76. Private Const ENABLE_WINDOW_INPUT = &H8
  77. 'For SetConsoleMode (output)
  78. Private Const ENABLE_PROCESSED_OUTPUT = &H1
  79. Private Const ENABLE_WRAP_AT_EOL_OUTPUT = &H2
  80.  
  81. '''''G L O B A L S'''''''''''''''''''''''''''''''''''
  82. Private hConsoleIn As Long ' The console's input handle
  83. Private hConsoleOut As Long ' The console's output handle
  84. Private hConsoleErr As Long ' The console's error handle
  85.  
  86. '''''M A I N'''''''''''''''''''''''''''''''''''''''''
  87. Private Sub Main()
  88. Dim szUserInput As String
  89.  
  90. AllocConsole ' Create a console instance
  91.  
  92. SetConsoleTitle "VB Console Example" 'Set the title on
  93.                                     'the console window
  94.  
  95. 'Get the console's handle
  96. hConsoleIn = GetStdHandle(STD_INPUT_HANDLE)
  97. hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE)
  98. hConsoleErr = GetStdHandle(STD_ERROR_HANDLE)
  99.  
  100. 'Print the prompt to the user. Use the vbCrLf to get
  101. 'to a new line.
  102. SetConsoleTextAttribute hConsoleOut, _
  103. FOREGROUND_RED Or FOREGROUND_GREEN _
  104. Or FOREGROUND_BLUE Or FOREGROUND_INTENSITY _
  105. Or BACKGROUND_BLUE
  106.  
  107. ConsolePrint "VB Console Example" & vbCrLf
  108. SetConsoleTextAttribute hConsoleOut, _
  109. FOREGROUND_RED Or FOREGROUND_GREEN _
  110. Or FOREGROUND_BLUE
  111. ConsolePrint "Enter your name--> "
  112.  
  113. 'Get the user's name
  114. szUserInput = ConsoleRead()
  115. If Not szUserInput = vbNullString Then
  116. ConsolePrint "Hello, " & szUserInput & "!" & vbCrLf
  117. Else
  118. ConsolePrint "Hello, whoever you are!" & vbCrLf
  119. End If
  120.  
  121. 'End the program
  122. ConsolePrint "Press enter to exit"
  123. Call ConsoleRead
  124.  
  125. FreeConsole ' Destroy the console
  126. End Sub
  127.  
  128. '''''F U N C T I O N S''''''''''''''''''''''''''''''''''
  129.  
  130. 'F+F+++++++++++++++++++++++++++++++++++++++++++++++++++
  131. ' Function: ConsolePrint
  132. '
  133. ' Summary: Prints the output of a string
  134. '
  135. ' Args: String ConsolePrint
  136. ' The string to be printed to the console's ouput buffer.
  137. '
  138. ' Returns: None
  139. '
  140. '-----------------------------------------------------
  141.  
  142. Private Sub ConsolePrint(szOut As String)
  143. WriteConsole hConsoleOut, szOut, Len(szOut), vbNull, vbNull
  144. End Sub
  145.  
  146. 'F+F++++++++++++++++++++++++++++++++++++++++++++++++++++
  147. ' Function: ConsoleRead
  148. '
  149. ' Summary: Gets a line of input from the user.
  150. '
  151. ' Args: None
  152. '
  153. ' Returns: String ConsoleRead
  154. ' The line of input from the user.
  155. '---------------------------------------------------F-F
  156.  
  157. Private Function ConsoleRead() As String
  158. Dim sUserInput As String * 256
  159. Call ReadConsole(hConsoleIn, sUserInput, _
  160.     Len(sUserInput), vbNull, vbNull)
  161. 'Trim off the NULL charactors and the CRLF.
  162. ConsoleRead = Left$(sUserInput, InStr(sUserInput, _
  163.     Chr$(0)) - 3)
  164. End Function
  165.  

Writing Console-Mode Applications in Visual Basic
« Last Edit: October 24, 2015, 07:38:56 PM by John »

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #6 on: October 25, 2015, 10:45:05 AM »
It seems I have gone full circle and the original console example post at the top of this thread is exactly what I needed. What makes this a better solution is it comes with a utility to change VB6 GUI .exe programs to look like a standard console applications. The second example has a few goodies I may include in the first example.
« Last Edit: October 25, 2015, 12:33:14 PM by John »

Offline Mike Lobanovsky

  • ON-HOLD
  • BASIC Developer
  • Posts: 261
Re: VB6 Console Applications
« Reply #7 on: October 25, 2015, 07:59:07 PM »
Now you can write colorful VB6 console submissions to my recent challenge on BP. ;)

As for Russian translation, hehe, this ain't no Russian Cyrillic alphabet you're seeing, that's the second half of ASCII table for Western Europe. :)

Actually not much meaningful info in there, just a usual blurb:

Code: Visual Basic
  1. ' ******************************************************************************
  2. ' *     Fire-Lines © 2013                                                      *
  3. ' *     Module:                                                                *
  4. ' *         EasyConsole                                                        *
  5. ' *     Description:                                                           *
  6. ' *         This module introduces revolutionary simple support                *
  7. ' *         for console application development using VB.                      *
  8. ' *     Author:                                                                *
  9. ' *         Vladislav Petrovsky (firehacker)                                   *
  10. ' *     Change Log:                                                            *
  11. ' *         *   2013-01-19  firehacker  Original commit                        *
  12. ' *                                                                            *
  13. ' *     Current version: 1.0.0                                                 *
  14. ' *                                                                            *
  15. ' ******************************************************************************
  16.  

What concerns zip downloads, you can't use them from a translated page. Google Translator tries to interpret the link rather than follow it. :D

Here is the link to the original Russian page. All the DLs seem to be working as expected. Refer to your PDF for what's in the links.

I'd still recommend using that approach. You'll have separate access to stdin, stdout and stderr (these are 3 different routes for reading from, writing to, and managing errors in, the Windows console). Dot notation is very VB-stylish. And you can always add more functionality, such as e.g. text coloration methods (i.e. commands), directly in the EasyConsole module.

Template installed as described in the PDF, open up a new EasyConsole-type project in the IDE, click the Object Browser toolbar button, select Scripting from the dropdown combobox, scroll down to the TextStream class and see what methods it has. That's what you can do with each of stdin, stdout and stderr on default.
« Last Edit: October 26, 2015, 04:48:17 AM by Mike Lobanovsky »
Mike
____________________________________________________________________
(3.6GHz Intel Core i5, 16GB RAM / nVidia GTX 1060Ti , 6GB VRAM / x64 Win7 Ult.)

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #8 on: October 25, 2015, 08:46:41 PM »
Thanks Mike!

That worked and something I should have realized as obvious.

It looks like a couple more steps but it's more robust than the first example I posted in this thread.
« Last Edit: October 25, 2015, 10:04:17 PM by John »

Offline Mike Lobanovsky

  • ON-HOLD
  • BASIC Developer
  • Posts: 261
Re: VB6 Console Applications
« Reply #9 on: October 26, 2015, 04:08:56 AM »
The couple of required steps to take will imply patching a copy of your existing VB6.exe (IDE) as a mixed CLI/GUI application using EDITBIN. If you have problems with this, PM or e-mail me the copy and I'll do it for you.

Everything installed and patched, you will create a new desktop shortcut (symlink, hehe) for VB6CON.exe alongside your existing VB6.exe and launch it whenever you want to create/debug a console app. Once launched, it will look exactly as your original IDE where you can edit code and create VB forms. But when you add an EasyConsole template, it will also respawn a console window for interaction with you in the immediate mode and also as an output/input screen for running and debugging your current project interactively using your usual Run/Pause/Stop buttons, menus or hotkeys. Unpatched VB6 IDE will not allow you to pause/resume execution and will crash.

Templated VB6CON IDE will also enable you to automatically compile your project directly to a console exe that wouldn't require any additional patching or distribution of dependencies or manual editing of the project file. When run outside the command prompt, each one of such exes would respawn their own console window and close it automatically on exit, or they would write directly to the existing common console window or screen if launched from the command prompt.
« Last Edit: October 26, 2015, 04:44:26 AM by Mike Lobanovsky »
Mike
____________________________________________________________________
(3.6GHz Intel Core i5, 16GB RAM / nVidia GTX 1060Ti , 6GB VRAM / x64 Win7 Ult.)

Offline John

  • Forum Support / SB Dev
  • Posts: 2416
    • ScriptBasic Open Source Project
Re: VB6 Console Applications
« Reply #10 on: October 26, 2015, 11:19:18 AM »
Quote from: Mike
If you have problems with this, PM or e-mail me the copy and I'll do it for you.

That would be cool! I'm running VB6 Enterprise if you need me to send you the .exe.

Thanks for that generous offer!

Offline Mike Lobanovsky

  • ON-HOLD
  • BASIC Developer
  • Posts: 261
Re: VB6 Console Applications
« Reply #11 on: October 26, 2015, 03:00:20 PM »
Not at all, John!

My weathered VB6 is of Russian localization bought at a local retailer's eons ago. Different locales can't be used in a common setup; VB6 is built around COM UUIDs of all sorts that are locale unique and matching in each distro. It could be a one way ticket only were your .exe Russian, or French, or Argentinian Spanish. :D
Mike
____________________________________________________________________
(3.6GHz Intel Core i5, 16GB RAM / nVidia GTX 1060Ti , 6GB VRAM / x64 Win7 Ult.)