private static bool IsHandleRedirected(IntPtr handle)
{
// If handle is not to a character device, we must be redirected:
uint fileType = Interop.Kernel32.GetFileType(handle);
if ((fileType & Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) != Interop.Kernel32.FileTypes.FILE_TYPE_CHAR)
return true;
// We are on a char device if GetConsoleMode succeeds and so we are not redirected.
return (!Interop.Kernel32.IsGetConsoleModeCallSuccessful(handle));
}