How to hide a Console Window in C# and VB.NET

To hide a Console Window in C# and VB.NET you can use the following snippet.

Sample C#

public static class Consoles
{
	[DllImport("user32.dll")]
	public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

	[DllImport("user32.dll")]
	public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

	public static void SetConsoleWindowVisibility(bool visible, IntPtr hWnd)
	{
		ShowWindow(hWnd, !visible ? 0 : 1);
	}
}

usage:

var hWnd = Consoles.FindWindow(null, Console.Title);
Consoles.SetConsoleWindowVisibility(false, hWnd);

Sample VB.NET

Public NotInheritable Class Consoles
	Private Sub New()
	End Sub
	<DllImport("user32.dll")> _
	Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr
	End Function

	<DllImport("user32.dll")> _
	Public Shared Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
	End Function

	Public Shared Sub SetConsoleWindowVisibility(visible As Boolean, hWnd As IntPtr)
		ShowWindow(hWnd, If(Not visible, 0, 1))
	End Sub
End Class

usage:

Dim hWnd = Consoles.FindWindow(Nothing, Console.Title)
Consoles.SetConsoleWindowVisibility(False, hWnd)

Please rate this snippet

How to hide a console window in C# and VB.NET

To hide a console window in C# and VB.NET you can use the following snippet.

Sample C#

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

public static void SetConsoleWindowVisibility(bool show, IntPtr hWnd)
{
	try
	{
		ShowWindow(hWnd, !show ? 0 : 1);
	}
	catch (Exception ex)
	{
		//handle the exception your way
	}
}

Example usage

var hWnd = Window.FindWindow(null, Console.Title);
if (hWnd != IntPtr.Zero) 
{
	SetConsoleWindowVisibility(showWindows, hWnd);
}

Sample VB.NET

<DllImport("user32.dll")> _
Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr
End Function

<DllImport("user32.dll")> _
Public Shared Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
End Function

Public Shared Sub SetConsoleWindowVisibility(show As Boolean, hWnd As IntPtr)
	Try
		ShowWindow(hWnd, If(Not show, 0, 1))
	Catch ex As Exception
        'handle the exception your way
	End Try
End Sub

Example usage

Dim hWnd = Window.FindWindow(Nothing, Console.Title)
If hWnd <> IntPtr.Zero Then
	SetConsoleWindowVisibility(showWindows, hWnd)
End If

Please rate this snippet