本文介绍了检测控制台窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能检测应用程序是否有一个控制台窗口?无论是已经使用AllocConsole,或者如果它是一个普通的控制台应用程序。

编辑:

解决方案(感谢HO1的答案):

 公共静态类ConsoleDetector
{
    私人常量UINT ATTACH_PARENT_PROCESS = 0x0ffffffff;
    私人const int的ERROR_ACCESS_DENIED = 5;
    [的DllImport(KERNEL32.DLL,SetLastError =真)
    私人静态外部布尔AttachConsole(UINT dwProcessId);
    [的DllImport(kernel32中,SetLastError =真)
    私人静态外部布尔FreeConsole();


    ///<总结>
    ///获取如果当前进程有一个控制台窗口。
    ///< /总结>
    公共静态布尔HasOne
    {
        得到
        {
            如果(AttachConsole(ATTACH_PARENT_PROCESS))
            {
                FreeConsole();
                返回false;
            }

            //如果调用进程已经连接到控制台,
            //错误code返回的是ERROR_ACCESS_DENIED
            返回Marshal.GetLastWin32Error()== ERROR_ACCESS_DENIED;
        }
    }
}
 

解决方案

做的也许有些更合适的方法,但我想你可以调用的并检查它是否失败, ERROR_INVALID_HANDLE (它将如果过程没有控制台)或没有。

Is it possible to detect if an application has an console window? Either by have used AllocConsole or if it's a regular console application.

Edit:

Solution (thanks to ho1's answer):

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;
        }
    }
}
解决方案

Probably some neater way of doing it but I suppose you could call AttachConsole and check if it fails with ERROR_INVALID_HANDLE (which it will if the process has no console) or not.

这篇关于检测控制台窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:28