【发布时间】:2010-10-25 10:02:11
【问题描述】:
是否可以检测应用程序是否有控制台窗口?要么使用过 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;
}
}
}
【问题讨论】:
-
当您说控制台窗口时,您指的是控制台应用程序还是只是一个窗口?
-
这不是很明显吗?首先我提到了 AllocConsole 方法,然后在我的问题中写了“控制台应用程序”。最后 ho1 给出了一个提到 AttachConsole 的答案 :)