Environment
- VB.net
- .NET Core 3.1
- Windows 10
Aim
Call a console window from forms, using AllocConsole() function. Especially, the case of calling a console application (project) from a form application (project) in a same solution of Visual Studio.
References
Code
Private Declare Function AllocConsole Lib "kernel32" () As Integer
Private Declare Function FreeConsole Lib "kernel32" () As Integer
Sub SomeName()
AllocConsole()
Console.SetOut(New StreamWriter(Console.OpenStandardOutput()) With {.AutoFlush = True})
'Set the size of the console window into an appropriate size.
Console.SetWindowSize(40, 20)
Console.SetBufferSize(80, 80)
Try
'(...)
Finally
FreeConsole()
End Try
End Sub
Note
-
AllocConsole()
function allocates a console window to the process. -
Console.SetOut(...)
defines the output stream of the console window. Without it, when the procedureSub SomeName
is called twice or more, functions likeConsole.Writeline(...)
would throw exceptions even though afterAllocConsole()
.- In some cases, specifying encoding may be needed, like
Dim enc As Text.Encoding = ...
Console.SetOut(New StreamWriter(Console.OpenStandardOutput(), enc) With {.AutoFlush = True})
- In some cases, specifying encoding may be needed, like
-
FreeConsole()
closes the console window.