Question: I have a console program that shouldn\'t be seen. (It resets IIS and deletes temp files.)
Right now I can manage to hide the window right after start like
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);
// see the comment below
private enum StdHandle
{
StdIn = -10,
StdOut = -11,
StdErr = -12
};
void HideConsole()
{
var ptr = GetStdHandle((int)StdHandle.StdOut);
if (!CloseHandle(ptr))
throw new Win32Exception();
ptr = IntPtr.Zero;
if (!FreeConsole())
throw new Win32Exception();
}
See more console-related API calls here