是否可以检测应用程序是否具有控制台窗口?要么使用AllocConsole,要么使用常规控制台应用程序。
修改
解决方案(感谢ho1的回答):
public static class ConsoleDetector
{
private const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;
private const int ERROR_ACCESS_DENIED = 5;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(uint dwProcessId);
[DllImport("kernel32", SetLastError = true)]
private static extern bool FreeConsole();
/// <summary>
/// Gets if the current process has a console window.
/// </summary>
public static bool HasOne
{
get
{
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
FreeConsole();
return false;
}
//If the calling process is already attached to a console,
// the error code returned is ERROR_ACCESS_DENIED
return Marshal.GetLastWin32Error() == ERROR_ACCESS_DENIED;
}
}
}
答案 0 :(得分:3)
可能有一些更简洁的方法,但我想你可以调用AttachConsole并检查它是否以ERROR_INVALID_HANDLE
失败(如果进程没有控制台,它将会失败)。