Exemplo n.º 1
0
        static unsafe IEnumerable <(string processName, int pid)> EnumerateProcesses()
        {
            int bytesReturned;
            var processIds = new int[2048];

            fixed(int *p = processIds)
            {
                if (!NativeMethodsWindows.EnumProcesses((IntPtr)p, sizeof(int) * processIds.Length, out bytesReturned))
                {
                    throw new Win32Exception("Failed to enumerate processes");
                }

                if (bytesReturned < 1)
                {
                    throw new Exception("Failed to enumerate processes");
                }
            }

            return(Enumerable.Range(0, bytesReturned / sizeof(int))
                   .Where(i => processIds[i] > 0)
                   .Select(i =>
            {
                try
                {
                    var hProcess = NativeMethodsWindows.OpenProcess(ProcessAccess.QueryLimitedInformation, false, processIds[i]);
                    if (hProcess == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    var sb = new StringBuilder(256);
                    var capacity = sb.Capacity;
                    if (!NativeMethodsWindows.QueryFullProcessImageName(hProcess, 0, sb, ref capacity))
                    {
                        throw new Win32Exception();
                    }

                    NativeMethodsWindows.CloseHandle(hProcess);

                    return (sb.ToString(), processIds[i]);
                }
                catch (Exception)
                {
                    return (default, processIds[i]);
Exemplo n.º 2
0
        public bool EnsureConsole()
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return(false);
            }

            if (Interlocked.CompareExchange(ref _consoleCreated, 1, 0) == 1)
            {
                return(false);
            }

            if (!NativeMethodsWindows.AttachConsole(-1))
            {
                NativeMethodsWindows.AllocConsole();
            }

            NativeMethodsWindows.GetStdHandle(StandardHandles.StdErrorHandle);
            NativeMethodsWindows.GetStdHandle(StandardHandles.StdOutputHandle);

            return(true);
        }