Algost
Algost

Reputation: 21

C# programm change mouse sensitivity

My goal is to create a little software to change dynamically the mouse speed of my mouse. I want to create a .dll of it and insert to my Unity Project to give the choice of my player to choose their mouse sensitivity.

On my research I found this topic with the code below:

public const UInt32 SPI_SETMOUSESPEED = 0x0071;

    [DllImport("User32.dll")]
    static extern Boolean SystemParametersInfo(
        UInt32 uiAction,
        UInt32 uiParam,
        UInt32 pvParam,
        UInt32 fWinIni);

    static void Main(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }

        SystemParametersInfo(
            SPI_SETMOUSESPEED,
            0,
            uint.Parse(args[0]),
            0);
    }

But, when I try to use this code in my Visual Studio I have this error:

System.IndexOutOfRangeException: 'The index is outside the bounds of the array.'

I tried to use the breakpoint, but this is not working, and I don't understand what is going in my arg[0].

I'm new in pur C# and I would like to know if I have to create a windows or handle input in order to have my program working.

Thanks :)

Upvotes: 0

Views: 1632

Answers (1)

pixelbadger
pixelbadger

Reputation: 1596

It appears that you have added this code to a console application. The string args[] parameter passed into the Main() method is an array of parameters taken from the command line.

For example, in the following command line: C:\> setmousespeed.exe 25, args will contain a single string value of "25". The line uint.Parse(args[0]) converts the string into an integer.

To use this method in a Unity application, you should convert the code to a publicly accessible method. An example of this is shown below.

public static class Utility
{
    public const UInt32 SPI_SETMOUSESPEED = 0x0071;

    [DllImport("User32.dll")]
    static extern Boolean SystemParametersInfo(
        UInt32 uiAction,
        UInt32 uiParam,
        UInt32 pvParam,
        UInt32 fWinIni);

    public static void SetMouseSpeed(unit speed)
    {
        for (int i = 0; i < args.Length; i++)
        {
            System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }

        SystemParametersInfo(
            SPI_SETMOUSESPEED,
            0,
            speed,
            0);
    }
}

Once imported into Unity, the above code can then be called as follows:

Utility.SetMouseSpeed(100);

To import into Unity you should also add this code to a Library (DLL) project, but I believe this is outside of the scope of this question.

Upvotes: 1

Related Questions