Пример #1
0
        public void UpdateMenu(SystemMenuItem menuItem)
        {
            var mii = new MENUITEMINFO
            {
                fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_FTYPE | MIIM_ID | MIIM_STATE | MIIM_STRING
            };

            mii.cbSize = (uint)Marshal.SizeOf(mii);

            PInvokeUtils.Try(() => GetMenuItemInfo(_hSysMenu, menuItem.Id, false, ref mii));

            if (menuItem.Enabled)
            {
                mii.fState &= (~MFS_DISABLED); // clear "disabled" flag
            }
            else
            {
                mii.fState |= MFS_DISABLED;    // set "disabled" flag
            }
            if (menuItem.Checked)
            {
                mii.fState |= MFS_CHECKED;    // set "checked" flag
            }
            else
            {
                mii.fState &= (~MFS_CHECKED); // clear "checked" flag
            }
            mii.fMask = MIIM_STATE;

            PInvokeUtils.Try(() => SetMenuItemInfo(_hSysMenu, menuItem.Id, false, ref mii));

            // TODO: From my observations, this function always returns false, even though it appears to succeed.
            //       Am I using it incorrectly?
            DrawMenuBar(_hSysMenu);
        }
Пример #2
0
 public void TestThrowsWin32Exception()
 {
     Assert.Throws <Win32Exception>(delegate
     {
         var result1 = PInvokeUtils.Try(() => JobObjectAPI.CloseHandle(IntPtr.Zero), result => result);
     });
 }
Пример #3
0
        /// <summary>
        ///     Determines if the given <paramref name="process"/> belongs to the specified
        ///     <paramref name="jobObjectHandle"/>.
        /// </summary>
        /// <param name="process">Process to check Job Object membership of.</param>
        /// <param name="jobObjectHandle">Job Object to check for membership.</param>
        /// <returns>
        ///     <c>true</c> if the given <paramref name="process"/> belongs to the specified
        ///     <paramref name="jobObjectHandle"/>; otherwise <c>false</c>.
        /// </returns>
        internal static bool IsProcessInJob(Process process, IntPtr jobObjectHandle)
        {
            var status = false;

            PInvokeUtils.Try(() => JobObjectAPI.IsProcessInJob(process.Handle, jobObjectHandle, out status));
            return(status);
        }
Пример #4
0
        public void KillOnClose()
        {
            var type   = JobObjectInfoClass.ExtendedLimitInformation;
            var limit  = CreateKillOnCloseJobObjectInfo();
            var length = GetKillOnCloseJobObjectInfoLength();

            PInvokeUtils.Try(() => WinAPI.SetInformationJobObject(_jobObjectHandle, type, ref limit, length));
        }
Пример #5
0
        /// <summary>
        ///     Gets the total amount of physical memory installed on the system.
        /// </summary>
        /// <returns>
        ///     Total amount of physical memory installed on the system in bytes.
        /// </returns>
        public static ulong GetPhysicalMemory()
        {
            int[] name               = { CTL_HW, HW_MEMSIZE };
            uint  nameLen            = (uint)name.Length;
            long  physicalMemory     = 0;
            uint  physicalMemorySize = sizeof(long);

            PInvokeUtils.Try(() => sysctl(name, nameLen, ref physicalMemory, ref physicalMemorySize, IntPtr.Zero, 0), retVal => retVal == SysctlSuccess);

            return((ulong)physicalMemory);
        }
Пример #6
0
//        [CanBeNull] // TODO
        public static Volume GetVolumeInformation(DirectoryInfo dir)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return(null);
            }

            uint serialNumber   = 0;
            uint maxLength      = 0;
            var  volumeFlags    = FileSystemFlags.NULL;
            var  volumeLabel    = new StringBuilder(256);
            var  fileSystemName = new StringBuilder(256);
            var  invocation     = string.Format("GetVolumeInformation({0})", dir == null ? "null" : string.Format("\"{0}\"", dir.FullName));

            try
            {
                PInvokeUtils.Try(() => GetVolumeInformation(dir.Root.FullName,
                                                            volumeLabel,
                                                            (uint)volumeLabel.Capacity,
                                                            ref serialNumber,
                                                            ref maxLength,
                                                            ref volumeFlags,
                                                            fileSystemName,
                                                            (uint)fileSystemName.Capacity));

                return(new Volume
                {
                    Label = volumeLabel.ToString(),
                    FileSystem = new FileSystem
                    {
                        Name = fileSystemName.ToString(),
                        Flags = volumeFlags
                    },
                    SerialNumber = serialNumber,
                    MaxFileNameLength = maxLength
                });
            }
            catch (Win32Exception e)
            {
                Logger.Error(string.Format("Invocation of native {0} function threw a Win32 exception", invocation), e);
            }
            catch (DllNotFoundException e)
            {
                Logger.Warn("Unable to locate kernel32.dll - OS is probably not Windows", e);
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0} threw an exception", invocation), e);
            }

            return(null);
        }
Пример #7
0
        /// <summary>
        ///     Gets the amount of available (free) memory on the system.
        /// </summary>
        /// <returns>
        ///     Amount of available (free) memory on the system in bytes.
        /// </returns>
        public static ulong GetAvailableMemory()
        {
            uint hostInfoCount = HOST_VM_INFO_COUNT;
            var  vmstat        = new vm_statistics_data_t();
            uint host_priv     = mach_host_self();

            PInvokeUtils.Try(() => host_statistics(host_priv, HostStatsType.HOST_VM_INFO, ref vmstat, ref hostInfoCount), result => result == KERN_SUCCESS);

            ulong physicalMemory = GetPhysicalMemory();

            double pagesTotal   = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count;
            double pagesFreePct = vmstat.free_count / pagesTotal;
            double bytesFree    = pagesFreePct * physicalMemory;

            return((ulong)bytesFree);
        }
Пример #8
0
        public void TestReturnsResult()
        {
            var jobObjectHandle = IntPtr.Zero;

            try
            {
                jobObjectHandle = PInvokeUtils.Try(() => JobObjectAPI.CreateJobObject(IntPtr.Zero, null), result => result != IntPtr.Zero);

                Assert.AreNotEqual(jobObjectHandle, IntPtr.Zero);
            }
            finally
            {
                if (jobObjectHandle != IntPtr.Zero)
                {
                    JobObjectAPI.CloseHandle(jobObjectHandle);
                }
            }
        }
Пример #9
0
        private static Process CreateProcessInSeparateJob(ProcessStartInfo startInfo)
        {
            var securityAttributes = new SECURITY_ATTRIBUTES
            {
                nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)),
                lpSecurityDescriptor = IntPtr.Zero,
                bInheritHandle       = false
            };

            var          environment                 = IntPtr.Zero;
            const bool   inheritHandles              = false;
            const string currentDirectory            = null;
            const ProcessCreationFlags creationFlags = ProcessCreationFlags.CREATE_BREAKAWAY_FROM_JOB;

            var startupInfo = new STARTUPINFO {
                cb = Marshal.SizeOf(typeof(STARTUPINFO))
            };
            var processInformation = new PROCESS_INFORMATION();

            PInvokeUtils.Try(() => JobObjectAPI.CreateProcess(startInfo.FileName,
                                                              startInfo.Arguments,
                                                              ref securityAttributes,
                                                              ref securityAttributes,
                                                              inheritHandles,
                                                              creationFlags,
                                                              environment,
                                                              currentDirectory,
                                                              ref startupInfo,
                                                              out processInformation));

            try
            {
                return(Process.GetProcessById(processInformation.dwProcessId));
            }
            catch (Exception e)
            {
                Logger.Error("Unable to get child process by ID.  " +
                             "Are you running in Visual Studio with Program Compatibility Assistant (PCA) enabled?  " +
                             "See http://stackoverflow.com/a/4232259/3205 for more information.", e);
                return(null);
            }
        }
Пример #10
0
        /// <summary>
        ///     Assigns the given process to this Job Object.
        /// </summary>
        /// <param name="process">Process to assign to this Job Object.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="process"/> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">
        ///     Thrown if <paramref name="process"/> already belongs to a Job Object.
        /// </exception>
        /// <exception cref="Win32Exception">
        ///     Thrown if the operating system was unable to assign <paramref name="process"/> to the Job Object.
        /// </exception>
        public void Assign(Process process)
        {
            if (process == null)
            {
                throw new ArgumentNullException("process");
            }

            if (AlreadyAssigned(process))
            {
                return;
            }

            if (HasJobObject(process))
            {
                throw new InvalidOperationException(
                          "Requested process already belongs to another job group.  Check http://stackoverflow.com/a/4232259/3205 for help.");
            }

            PInvokeUtils.Try(() => WinAPI.AssignProcessToJobObject(_jobObjectHandle, process.Handle));
        }
Пример #11
0
        /// <summary>
        ///     Frees managed and unmanaged resources.
        /// </summary>
        /// <param name="freeManagedObjectsAlso">
        ///     Free managed resources.  Should only be set to <c>true</c> when called from <see cref="Dispose"/>.
        /// </param>
        /// <exception cref="Win32Exception">
        ///     Thrown if the handle to the Job Object could not be released.
        /// </exception>
        /// <seealso cref="http://stackoverflow.com/a/538238/467582"/>
        private void Dispose(bool freeManagedObjectsAlso)
        {
            // Free unmanaged resources
            // ...

            // Free managed resources too, but only if I'm being called from Dispose()
            // (If I'm being called from Finalize then the objects might not exist anymore)
            if (freeManagedObjectsAlso)
            {
                if (_disposed)
                {
                    return;
                }
                if (_jobObjectHandle == IntPtr.Zero)
                {
                    return;
                }

                _disposed = true;

                PInvokeUtils.Try(() => WinAPI.CloseHandle(_jobObjectHandle));
            }
        }
Пример #12
0
 public void AppendMenu(SystemMenuItem menuItem)
 {
     PInvokeUtils.Try(() => AppendMenu(_hSysMenu, MF_STRING, menuItem.Id, menuItem.Text));
     _items.Add(menuItem);
 }
Пример #13
0
 /// <exception cref="Win32Exception">
 ///     Thrown if the operating system was unable to create a new Job Object.
 /// </exception>
 public JobObject()
 {
     _jobObjectHandle = PInvokeUtils.Try(() => WinAPI.CreateJobObject(IntPtr.Zero, null));
 }
Пример #14
0
 public void InsertMenu(uint position, SystemMenuItem menuItem)
 {
     PInvokeUtils.Try(() => InsertMenu(_hSysMenu, position, MF_BYPOSITION | MF_STRING, menuItem.Id, menuItem.Text));
     _items.Add(menuItem);
 }
Пример #15
0
 public void AppendSeparator()
 {
     PInvokeUtils.Try(() => AppendMenu(_hSysMenu, MF_SEPARATOR, 0, string.Empty));
 }
Пример #16
0
 public void AppendMenu(IWindowMenuItem menuItem)
 {
     PInvokeUtils.Try(() => SystemMenuAPI.AppendMenu(_hSysMenu, MenuFlags.MF_STRING, menuItem.Id, menuItem.Text));
     _items.Add(menuItem);
 }
Пример #17
0
 public void InsertSeparator(uint position)
 {
     PInvokeUtils.Try(() => SystemMenuAPI.InsertMenu(_hSysMenu, position, MenuFlags.MF_BYPOSITION | MenuFlags.MF_SEPARATOR, 0, string.Empty));
 }
Пример #18
0
 public void InsertMenu(uint position, IWindowMenuItem menuItem)
 {
     PInvokeUtils.Try(() => SystemMenuAPI.InsertMenu(_hSysMenu, position, MenuFlags.MF_BYPOSITION | MenuFlags.MF_STRING, menuItem.Id, menuItem.Text));
     _items.Add(menuItem);
 }
Пример #19
0
 public void AppendSeparator()
 {
     PInvokeUtils.Try(() => SystemMenuAPI.AppendMenu(_hSysMenu, MenuFlags.MF_SEPARATOR, 0, string.Empty));
 }