Hide/Show Console window in .NET 2.0 and higher (black window)

When working with .Net Console application, one issue may occurred is how to hide the console screen ( the black window ). In my case, my console application call to show an Window Form and the console need to be hide for convenient handling. And when needed, we also unhide the console.

See runnable example below :


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MyNamespace
{
class Program
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

[STAThread]
static void Main(string[] args)
{
// My example context is when app run with no parameters
// application launch an UI to waiting command from it.
if (arrArgs.Count == 0)
{
// Display manage UI and hide console
HideConsole();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
else
{
// Handle parameters ...
}
}

static void HideConsole()
{
IntPtr hWnd = FindWindow(null, Console.Title);
if(hWnd != IntPtr.Zero)
{
ShowWindow(hWnd, 0); // 0 = SW_HIDE
}
}
static void ShowConsole()
{
IntPtr hWnd = FindWindow(null, Console.Title);
if (hWnd != IntPtr.Zero)
{
ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA
}
}
}
}


Hope this useful for you.
Happy harvest exp.
Moongy.

1 nhận xét:

Cheap laptop on June 5, 2009 at 2:01 AM said...

Thank, i'll try this

 

Coding experience share Copyright © 2010 | Designed by Ipietoon for Free Blogger Template