【发布时间】:2020-04-01 02:47:04
【问题描述】:
全部!
请就我的问题提供任何建议:我构建了 GUI WinForms 应用程序,现在我想将控制台附加到它。我发现这并不像以前那么容易。但我在这里找到了很好的解决方案:How do I show a console output/window in a forms application? 下面的代码来自rag 答案。
using System;
using System.Runtime.InteropServices;
namespace SomeProject
{
class GuiRedirect
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(StandardHandle nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern FileType GetFileType(IntPtr handle);
private enum StandardHandle : uint
{
Input = unchecked((uint)-10),
Output = unchecked((uint)-11),
Error = unchecked((uint)-12)
}
private enum FileType : uint
{
Unknown = 0x0000,
Disk = 0x0001,
Char = 0x0002,
Pipe = 0x0003
}
private static bool IsRedirected(IntPtr handle)
{
FileType fileType = GetFileType(handle);
return (fileType == FileType.Disk) || (fileType == FileType.Pipe);
}
public static void Redirect()
{
if (IsRedirected(GetStdHandle(StandardHandle.Output)))
{
var initialiseOut = Console.Out;
}
bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error));
if (errorRedirected)
{
var initialiseError = Console.Error;
}
AttachConsole(-1);
if (!errorRedirected)
SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output));
}
}
除了一个缺点外,这段代码的作用就像魅力:非拉丁字母以奇怪的编码输出到控制台(但如果重定向到文件,它们是正确的编码)。我需要重定向 StdOut 和 StdErr,如果我更改代码的任何部分,它就会停止重定向。
【问题讨论】:
-
你看SetConsoleOutputCP了吗?
-
我猜。但是您使用的字体可能不支持编码模式。请参阅:pinvoke.net/default.aspx/kernel32.SetConsoleFont
-
为什么你想要一个控制台?这感觉像是 XY 问题 (meta.stackexchange.com/questions/66377/what-is-the-xy-problem)?
-
@mjw:将控制台附加到 GUI 进程是允许应用程序转储诊断信息的常用方法。
-
确实如此。如果我们能确定这就是@AlfofMelmac 想要的……