Пример #1
0
        /// <summary>
        /// Gets the dpi of the display. If the window is not on any monitor the primary monitor's
        /// dpi is returned instead.
        /// <para/>
        /// On Windows version lower than 8, the dpi is the same for all monitors.
        /// </summary>
        /// <param name="windowHandle">The handle of the window displayed by the monitor</param>
        /// <returns>The dpi of the current display</returns>
        public static MonitorDpi GetDpi(IntPtr windowHandle)
        {
            if ((Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 2) || Environment.OSVersion.Version.Major >= 10)
            {
                var monitor = UnsafeNative.MonitorFromWindow(windowHandle, MonitorOptions.MONITOR_DEFAULTTONULL);

                if (monitor == IntPtr.Zero)
                {
                    monitor = UnsafeNative.MonitorFromPoint(new UnsafeNative.POINT {
                        x = 0, y = 0
                    }, MonitorOptions.MONITOR_DEFAULTTOPRIMARY);
                }

                UnsafeNative.GetDpiForMonitor(monitor, UnsafeNative.DpiType.Effective, out uint dpiX, out uint dpiY);

                return(new MonitorDpi {
                    x = dpiX, y = dpiY
                });
            }
            else
            {
                var desktop = Graphics.FromHwnd(IntPtr.Zero).GetHdc();

                var logicalPixelsx = (uint)UnsafeNative.GetDeviceCaps(desktop, UnsafeNative.DeviceCap.LOGPIXELSX);
                var logicalPixelsy = (uint)UnsafeNative.GetDeviceCaps(desktop, UnsafeNative.DeviceCap.LOGPIXELSY);

                return(new MonitorDpi {
                    x = logicalPixelsx, y = logicalPixelsy
                });
            }
        }
Пример #2
0
        private static IntPtr HandleMessages(IntPtr handle, int message, IntPtr wParameter, IntPtr lParameter, ref Boolean handled)
        {
            var data = UnsafeNative.GetMessage(message, lParameter);

            if (data != null)
            {
                if (Application.Current.MainWindow == null)
                {
                    return(IntPtr.Zero);
                }

                if (Application.Current.MainWindow.WindowState == WindowState.Minimized)
                {
                    Application.Current.MainWindow.WindowState = WindowState.Normal;
                }

                if ([email protected])
                {
                    UnsafeNative.ActivateWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle);
                }

                var args = data.Split([email protected]);
                [email protected](args);
                handled = true;
            }

            return(IntPtr.Zero);
        }
Пример #3
0
 /// <summary>
 /// Gets the path of the user's profile picture
 /// </summary>
 /// <param name="username">The username</param>
 /// <returns>The full path of the user's profile picture</returns>
 public static string GetUserTilePath(string username)
 {
     try
     {
         var stringBuilder = new StringBuilder(1000);
         UnsafeNative.GetUserTilePath(username, 0x80000000, stringBuilder, stringBuilder.Capacity);
         return(stringBuilder.ToString());
     }
     catch
     {
         throw;
     }
 }
Пример #4
0
        private static string GetShortPath(string longPath)
        {
            if (!File.Exists(longPath) && !Directory.Exists(longPath))
            {
                throw new IOException("Unable to shortend path of a directory or a file that does not exist.: " + longPath);
            }

            var shortPath = new StringBuilder(255);

            UnsafeNative.GetShortPathName(longPath, shortPath, 255);

            return(shortPath.ToString());
        }
Пример #5
0
        /// <summary>
        /// Gets the bounds of the monitor that contains the defined window
        /// </summary>
        /// <param name="windowHandle">The handle of the window displayed by the monitor</param>
        /// <returns>
        /// Returns the bounds of the monitor. Returns null if window is not on any monitor.
        /// </returns>
        public static Rect?GetMonitorBounds(IntPtr windowHandle)
        {
            var monitor = UnsafeNative.MonitorFromWindow(windowHandle, MonitorOptions.MONITOR_DEFAULTTONULL);

            if (monitor != IntPtr.Zero)
            {
                UnsafeNative.MONITORINFO monitorInfo = new UnsafeNative.MONITORINFO();
                UnsafeNative.GetMonitorInfo(monitor, monitorInfo);
                UnsafeNative.RECT rcWorkArea    = monitorInfo.rcWork;
                UnsafeNative.RECT rcMonitorArea = monitorInfo.rcMonitor;

                return(new Rect(rcMonitorArea.left, rcMonitorArea.top, Math.Abs(rcMonitorArea.left - rcMonitorArea.right), Math.Abs(rcMonitorArea.bottom - rcMonitorArea.top)));
            }

            return(null);
        }
        private static void RequestShutdownPrivilege()
        {
            // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/shutting_down.asp
            // https://www.codeproject.com/Articles/6164/A-ServiceInstaller-Extension-That-Enables-Recovery

            var processToken    = IntPtr.Zero;
            var currentProcess  = Process.GetCurrentProcess().Handle;
            var tokenPrivileges = new UnsafeNative.TokenPrivileges();

            try
            {
                if (!UnsafeNative.OpenProcessToken(
                        currentProcess,
                        UnsafeNative.TOKEN_ADJUST_PRIVILEGES | UnsafeNative.TOKEN_QUERY,
                        ref processToken))
                {
                    throw new AccessTokenException("Unable to open process token");
                }

                long lpUid = 0;
                UnsafeNative.LookupPrivilegeValue(null, UnsafeNative.SE_SHUTDOWN_NAME, ref lpUid);

                tokenPrivileges.PrivilegeCount        = 1;
                tokenPrivileges.Privileges.Luid       = lpUid;
                tokenPrivileges.Privileges.Attributes = UnsafeNative.SE_PRIVILEGE_ENABLED;

                int returnLength = 0;
                UnsafeNative.AdjustTokenPrivileges(processToken, false, ref tokenPrivileges, 0, IntPtr.Zero, ref returnLength);

                if (UnsafeNative.GetLastError() != 0)
                {
                    throw new UnauthorizedAccessException("Failed to grant shutdown privilege");
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (processToken != IntPtr.Zero)
                {
                    UnsafeNative.CloseHandle(processToken);
                }
            }
        }
        public static WindowsImpersonationContext Impersonate(this PrincipalContext principalContext, string username, string password, LogonType logonType)
        {
            if (username == null)
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("The parameter cannot be empty", nameof(username));
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("The parameter cannot be empty", nameof(password));
            }

            SafeTokenHandle handle = null;

            try
            {
                if (!UnsafeNative.LogonUser(username, principalContext.Name, password, (int)logonType, 3 /* LOGON32_PROVIDER_WINNT50 */, out handle))
                {
                    throw new PrincipalOperationException("Could not impersonate the user.", Marshal.GetLastWin32Error());
                }

                var identity = WindowsIdentity.Impersonate(handle.DangerousGetHandle());
                return(identity);
            }
            catch
            {
                throw;
            }
            finally
            {
                handle?.Dispose();
            }
        }
Пример #8
0
        /// <summary>
        /// Sent to a window when the size or position of the window is about to change. An
        /// application can use this message to override the window's default maximized size and
        /// position, or its default minimum or maximum tracking size.
        /// </summary>
        /// <param name="windowHandle">The handle of the window displayed by the monitor</param>
        /// <param name="lParam">Additional message-specific information</param>
        public static void WmGetMinMaxInfo(IntPtr windowHandle, IntPtr lParam)
        {
            var mmi = (UnsafeNative.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(UnsafeNative.MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor
            var monitor = UnsafeNative.MonitorFromWindow(windowHandle, MonitorOptions.MONITOR_DEFAULTTONEAREST);

            if (monitor != System.IntPtr.Zero)
            {
                UnsafeNative.MONITORINFO monitorInfo = new UnsafeNative.MONITORINFO();
                UnsafeNative.GetMonitorInfo(monitor, monitorInfo);
                UnsafeNative.RECT rcWorkArea    = monitorInfo.rcWork;
                UnsafeNative.RECT rcMonitorArea = monitorInfo.rcMonitor;
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x     = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y     = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }
Пример #9
0
 /// <summary>
 /// Determines if the window is shown in any of the monitors.
 /// </summary>
 /// <param name="windowHandle">The handle of the window displayed by the monitor</param>
 /// <returns>true if the window is displayed on any monitor; otherwise false</returns>
 public static bool WindowIsInAnyMonitor(IntPtr windowHandle) =>
 // If MonitorFromWindow has returned zero, we are sure that the window is not in any of
 // our monitors
 UnsafeNative.MonitorFromWindow(windowHandle, MonitorOptions.MONITOR_DEFAULTTONULL) != IntPtr.Zero;
Пример #10
0
 /// <summary>
 /// Determines whether a path represents a network resource.
 /// </summary>
 /// <param name="path">The path to test</param>
 /// <returns>True if the given path is a network path; otherwise false</returns>
 public static bool IsNetworkPath(this DirectoryInfo path) => UnsafeNative.PathIsNetworkPath(path.FullName);
        internal static void SetServiceFailureActions(this ServiceInstaller serviceInstaller, FailureActions failureActions)
        {
            if (serviceInstaller == null)
            {
                throw new ArgumentNullException(nameof(serviceInstaller));
            }

            if (failureActions == null)
            {
                throw new ArgumentNullException(nameof(failureActions));
            }

            // If any of the of the actions is reboot,
            // we need to request shutdown priviledges from the system
            if (failureActions.FirstFailure == RecoveryAction.Reboot |
                failureActions.SecondFailure == RecoveryAction.Reboot |
                failureActions.SubsequentFailure == RecoveryAction.Reboot)
            {
                RequestShutdownPrivilege();
            }

            var actionsPointer = IntPtr.Zero;
            var serviceManager = IntPtr.Zero;
            var serviceLock    = IntPtr.Zero;
            var serviceHandle  = IntPtr.Zero;

            try
            {
                var restartServiceAfter = (int)failureActions.RestartServiceAfter.TotalMilliseconds;
                var actions             = new int[6];
                // First failure
                actions[0] = (int)failureActions.FirstFailure;
                actions[1] = restartServiceAfter;
                // Second failure
                actions[2] = (int)failureActions.SecondFailure;
                actions[3] = restartServiceAfter;
                // subsequent failure
                actions[4] = (int)failureActions.SubsequentFailure;
                actions[5] = restartServiceAfter;

                actionsPointer = Marshal.AllocHGlobal(24 /* 3 x 2 x 4 */);
                Marshal.Copy(actions, 0, actionsPointer, 6);

                var serviceFailureActions = new UnsafeNative.ServiceFailureActions();
                serviceFailureActions.cActions      = 3;
                serviceFailureActions.dwResetPeriod = (int)failureActions.ResetFailCountAfter.TotalSeconds;
                serviceFailureActions.lpCommand     = $"{failureActions.RunProgram} {failureActions.RunProgramArguments}";
                serviceFailureActions.lpRebootMsg   = string.Empty;
                serviceFailureActions.lpsaActions   = actionsPointer.ToInt32();

                serviceManager = UnsafeNative.OpenSCManager(null, null, UnsafeNative.SC_MANAGER_ALL_ACCESS);

                if (serviceManager.ToInt32() <= 0)
                {
                    throw new ServiceManagerException("Unable to open the service manager.");
                }

                serviceLock = UnsafeNative.LockServiceDatabase(serviceManager);

                if (serviceLock.ToInt32() <= 0)
                {
                    throw new ServiceManagerException("Unable to lock the service database.");
                }

                serviceHandle = UnsafeNative.OpenService(serviceManager, serviceInstaller.ServiceName, UnsafeNative.SERVICE_ALL_ACCESS);

                if (serviceHandle.ToInt32() <= 0)
                {
                    throw new ServiceManagerException($"Unable to open the '{serviceInstaller.ServiceName}' service.");
                }

                if (!UnsafeNative.ChangeServiceFailureActions(serviceHandle, UnsafeNative.SERVICE_CONFIG_FAILURE_ACTIONS, ref serviceFailureActions))
                {
                    var lastError = UnsafeNative.GetLastError();
                    if (lastError == UnsafeNative.ERROR_ACCESS_DENIED)
                    {
                        throw new UnauthorizedAccessException("Access denied while setting failure actions.");
                    }

                    throw new ServiceManagerException("An error has occured while setting failure actions. Error code: " + lastError);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (serviceManager != IntPtr.Zero && serviceLock != IntPtr.Zero)
                {
                    UnsafeNative.UnlockServiceDatabase(serviceLock);
                }

                if (actionsPointer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(actionsPointer);
                }

                if (serviceHandle != IntPtr.Zero)
                {
                    UnsafeNative.CloseServiceHandle(serviceHandle);
                }

                if (serviceManager != IntPtr.Zero)
                {
                    UnsafeNative.CloseServiceHandle(serviceManager);
                }
            }
        }