有时需要窗体来调出控制台,显示日志文件中正在发生的记录。
这时就需要用AllocConsole()
[DllImport("Kernel32.dll")]
private staticextern bool AllocConsole();
[DllImport("kernel32.dll",
EntryPoint ="GetStdHandle",
SetLastError =true,
CharSet =CharSet.Auto,
CallingConvention =CallingConvention.StdCall)]
private staticextern IntPtr GetStdHandle(int nStdHandle);
private constint STD_OUTPUT_HANDLE = -11;
privatevoid setOutput()
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(Console.OutputEncoding.CodePage);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush =true;
Console.SetOut(standardOutput);
}