프로그래밍

vb.net 콘솔 FreeConsole AllocConsole 재사용하기

반응형

비베닷넷 윈도우 폼에서 콘솔창을 실행하고 닫고, 콘솔창이 필요할 때 재사용하는 방법(?)입니다.

재사용이라는 단어가 좀 그렇긴 한데 암튼 콘솔창을 다시 띄우는 방법입니다.

 

윈도우 폼에는 두개의 버튼이 필요합니다.

 

CreateConsole(AllocConsole) 콘솔화면 띄우는 버튼

FreeConsole 콘솔화면 닫는 버튼

 

 

CreateConsole 버튼을 클릭하면 아래와 같은 콘솔화면이 나옵니다.

아래 이미지의 우측 상단에 보면 닫기 버튼이 비활성화 되어 있습니다. 콘솔화면을 띄우면서 닫기 버튼을 비활성화합니다.

 

콘솔화면이 떠 있는 상태에서 창을 마우스클릭으로 닫을 수는 없지만 Alt + F4 는 막을 수 없습니다.

이것까지 막으려면 키보드 후킹을 해야합니다.

 

 

프로그램의 전체 소스입니다. 티스토리는 탭이 먹히지를 않네요.

제가 사용법을 잘 모르는 건지 아무튼 코드가 보기가 어렵습니다.

 

<DllImport("kernel32.dll", SetLastError:=True)> _

Shared Function FreeConsole() As Boolean

End Function

 

<DllImport("kernel32.dll", SetLastError:=True)> _

Public Shared Function GetConsoleWindow() As IntPtr

End Function

 

<DllImport("user32.dll")> _

Private Shared Function GetSystemMenu(hWnd As IntPtr, bRevert As Boolean) As IntPtr

End Function

 

<DllImport("user32.dll")> _

Shared Function DeleteMenu(ByVal hMenu As IntPtr, ByVal uPosition As UInteger, ByVal uFlags As UInteger) As Boolean

End Function

 

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _

Private Shared Function SetWindowText(ByVal hwnd As IntPtr, ByVal lpString As String) As Boolean

End Function

<DllImport("kernel32.dll", SetLastError:=True)> _

Shared Function AllocConsole() As <MarshalAs(UnmanagedType.Bool)> Boolean

End Function

 

Public Shared Sub CreateConsole()

AllocConsole()

Dim writer As TextWriter = New StreamWriter(Console.OpenStandardOutput()) With {.AutoFlush = True}

Console.SetOut(writer)

End Sub

 

Private Sub btn_CreateConsole_Click(sender As Object, e As EventArgs) Handles btn_CreateConsole.Click

Const SC_CLOSE As Integer = &HF060

Const MF_BYCOMMAND As Integer = 0

CreateConsole()

Dim MyConsole As IntPtr = GetConsoleWindow()

System.Threading.Thread.Sleep(11)

SetWindowText(GetConsoleWindow, "Title Name")

Dim hmenu As IntPtr = GetSystemMenu(MyConsole, False)

DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND)

Console.WriteLine("Console Start")

End Sub

 

Private Sub btn_FreeConsole_Click(sender As Object, e As EventArgs) Handles btn_FreeConsole.Click

FreeConsole()

End Sub

반응형