0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

<VB.net> Memo: AllocConsole() (.NET Core)

Posted at

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 procedure Sub SomeName is called twice or more, functions like Console.Writeline(...) would throw exceptions even though after AllocConsole().

    • In some cases, specifying encoding may be needed, like
      Dim enc As Text.Encoding = ...
      Console.SetOut(New StreamWriter(Console.OpenStandardOutput(), enc) With {.AutoFlush = True})
  • FreeConsole() closes the console window.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?