Spring – Rev 1

Subversion Repositories:
Rev:
using System;
using System.Runtime.InteropServices;

namespace Spring.Utilities
{
    /// <summary>
    ///     Setting and unsetting of mouse parameters such as the mouse acceleration and the mouse enhanced precision.
    /// </summary>
    /// <remarks>
    ///     https://stackoverflow.com/questions/24737775/toggle-enhance-pointer-precision and
    ///     https://stackoverflow.com/questions/2931122/dynamically-changing-mouse-speed
    /// </remarks>
    public class MouseOptions
    {
#region Static Fields and Constants

        public const int SPI_GET_MOUSE_SPEED = 112;

        public const int SPI_SET_MOUSE_SPEED = 113;

        public const int SPI_GET_MOUSE_ENHANCED_PRECISION = 0x0003;

        public const int SPI_SET_MOUSE_ENHANCED_PRECISION = 0x0004;

        private const int DEFAULT_MOUSE_SPEED = 10;

#endregion

#region Public Methods

        [DllImport("user32.dll")]
        public static extern int SystemParametersInfo(int uAction, int uParam, IntPtr lpvParam, int fuWinIni);

        public static void SetDefaultMouseSpeed()
        {
            SetMouseSpeed(DEFAULT_MOUSE_SPEED);
        }

        public static void SetMouseEnhancedPrecision(bool set)
        {
            var mouseParams = new int[3];

            SystemParametersInfo(SPI_GET_MOUSE_ENHANCED_PRECISION,
                0,
                GCHandle.Alloc(mouseParams, GCHandleType.Pinned)
                        .AddrOfPinnedObject(),
                0);

            mouseParams[2] = set ? 1 : 0;

            SystemParametersInfo(SPI_SET_MOUSE_ENHANCED_PRECISION,
                0,
                GCHandle.Alloc(mouseParams, GCHandleType.Pinned)
                        .AddrOfPinnedObject(),
                0);
        }

        public static bool GetMouseEnhancedPrecision()
        {
            var mouseParams = new int[3];

            SystemParametersInfo(SPI_GET_MOUSE_ENHANCED_PRECISION,
                0,
                GCHandle.Alloc(mouseParams, GCHandleType.Pinned)
                        .AddrOfPinnedObject(),
                0);

            return mouseParams[2] == 1;
        }

        public static int GetMouseSpeed()
        {
            var ptr = Marshal.AllocCoTaskMem(4);
            SystemParametersInfo(SPI_GET_MOUSE_SPEED, 0, ptr, 0);
            var intSpeed = Marshal.ReadInt32(ptr);
            Marshal.FreeCoTaskMem(ptr);

            return intSpeed;
        }

        public static bool SetMouseSpeed(int intSpeed)
        {
            var ptr = new IntPtr(intSpeed);

            var b = SystemParametersInfo(SPI_SET_MOUSE_SPEED, 0, ptr, 0);

            return b == 1;
        }

#endregion
    }
}