How do I swap left and right mouse buttons in .NET (preferably C#)? Basically the result should be the same as if the user checked the "Switch primary and secondary buttons" checkbox in the Mouse Properties through the control panel. I'm dealing with Windows XP, in case that makes a difference.
Asked
Active
Viewed 5,445 times
7
-
what do u mean by swapping... do u want to do a system-level swap or a swap for your own application? – Aamir Mar 17 '09 at 11:55
3 Answers
15
You can use a Windows API call to SwapMouseButton
:
using System.Runtime.InteropServices;
// ...
[DllImport("user32.dll")]
public static extern Int32 SwapMouseButton(Int32 bSwap);
// ...
// Swap it.
SwapMouseButton(1);
// Back to normal.
SwapMouseButton(0);

John Feminella
- 303,634
- 46
- 339
- 357
-
thanks. may want to add that you need "using System.Runtime.InteropServices;" – Eugene Katz Mar 17 '09 at 12:08
-
Whoops; I did indeed neglect to mention that. I'll add it for future reference. – John Feminella Mar 17 '09 at 12:16
-
This works but the state is not saved after user logs out. To have the swap state remembered you have to use Porges's solution with the registry. – foka Feb 24 '13 at 11:53
4
Something like this:
using Microsoft.Win32;
var key = Registry.CurrentUser.CreateSubKey("Control Panel\\Mouse\\");
var newValue = key.GetValue("SwapMouseButtons");
if (newValue == null) newValue = "1";
else newValue = Int32.Parse(newValue) == 1 ? "0" : "1";
key.SetValue("SwapMouseButtons", newValue, RegistryValueKind.String);

porges
- 30,133
- 4
- 83
- 114