Beispiel #1
0
        /// <exception cref="CloseProcessException">If the window process closing fails</exception>
        public static string GetForegroundWindowExeModulePath()
        {
            string result        = null;
            uint   processId     = GetForegroundWindowProcessID();
            IntPtr processHandle = WinAPIDeclarations.OpenProcess(
                ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead, true, (int)processId);

            if (processHandle != IntPtr.Zero)
            {
                int           size   = 1024;
                StringBuilder buffer = new StringBuilder(DefaultBufferSize);
                uint          length = WinAPIDeclarations.GetModuleFileNameEx(processHandle, IntPtr.Zero, buffer, size);
                // returns length of the string copied to the buffer (0 if failed)
                if (length > 0)
                {
                    result = buffer.ToString();
                }

                bool closed = WinAPIDeclarations.CloseHandle(processHandle);
                if (!closed)
                {
                    throw new CloseProcessException();
                }
            }
            return(result);
        }