Lock those Mouse Buttons!

I got really tired of having my mouse buttons swap on me at random times. I’m running Windows 10 on two separate laptops, an X1 and a Yoga and I see the same issue on both of them. After not using the machine overnight, or sometimes from one hour to the next, I’ll simply find that my mouse buttons have been swapped for no apparent reason. Searching the web, I see reports of this going as far back as 2015 and apparently no one seems to be able to fix this.

Until now. So far, this is working for me. It’s a little program which runs invisibly in the background. It doesn’t eliminate the problem but it brute-forces fixes it. If it senses that the buttons have been swapped, it will swap them back within seconds. Put this in your Windows Startup folder to launch automatically. So far this is working beautifully, eliminating this annoyance for me and I hope you will find this to be helpful as well!

using System;
using System.Configuration;
using Microsoft.Win32;
using System.Threading;
using System.Runtime.InteropServices;

namespace ButtonLocker
{
    static class Program
    {
        [DllImport("user32.dll")]
        public static extern Int32 SwapMouseButton(Int32 bSwap);

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            int swapVal = Convert.ToInt32(ConfigurationManager.AppSettings.Get("swapVal"));
            int sleepMS = Convert.ToInt32(ConfigurationManager.AppSettings.Get("sleepMS"));

            while (!false)
            {
                try
                {
                    SwapMouseButton(swapVal);

                    var key = Registry.CurrentUser.CreateSubKey("Control Panel\\Mouse\\");
                    int? currSetting = Convert.ToInt32(key.GetValue("SwapMouseButtons"));

                    if (currSetting == null || currSetting != swapVal)
                    {
                        key.SetValue("SwapMouseButtons", swapVal, RegistryValueKind.String);
                    }

                    Thread.Sleep(sleepMS);
                }
                catch { }
            }
        }
    }
}

Here’s the configuration file. Adjust according to your needs.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <appSettings>
    <add key="swapVal" value="0"/>
    <add key="sleepMS" value="3000"/>
  </appSettings>
</configuration>