torgabor
torgabor

Reputation: 364

Trouble calling SystemParametersInfo

Recently I've been trying to call the SystemParametersInfo method from managed code, without any success.

The problem is that, after calling the method, the method returns false (indicating failure), however GetLastError (retrieved by Marshal.GetLastWin32Error()) is 0.

I tried to invoke the method from C++ as a test (with the exact same parameters), and it works completely fine from there.

The P/Invoke declaration of the method is this:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SystemParametersInfo(SPI uiAction, int uiParam, ref STICKYKEYS pvParam, SPIF fWinIni);

internal struct STICKYKEYS 
{
  public int cbSize;
  public int dwFlags;
}

And the invocation is as follows:

NativeMethods.STICKYKEYS stickyKeys = default(NativeMethods.STICKYKEYS);
bool result = NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_GETSTICKYKEYS, StickyKeysSize, ref stickyKeys, 0);
int error = Marshal.GetLastWin32Error();

The SPI.SPI_GETSTICKYKEYS is0x003A (as seen on MSDN).

Here the result is false, and the error returned is 0.
Also this is complied as a 64-bit executable if that matters.

I'm completely at my wit's end, do you have any idea what I might be doing wrong?

Upvotes: 4

Views: 1234

Answers (1)

torgabor
torgabor

Reputation: 364

As GSerg pointed it out to me, my issue was that I need to pass in the size of the struct both directly as a parameter, and as the cbSize member of the struct that I passed in by reference. The correct code is:

        int stickyKeysSize = Marshal.SizeOf(typeof (NativeMethods.STICKYKEYS));
        NativeMethods.STICKYKEYS stickyKeys = new NativeMethods.STICKYKEYS {cbSize = stickyKeysSize, dwFlags = 0};
        bool result = NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_GETSTICKYKEYS, stickyKeysSize, ref stickyKeys, 0);
        if (!result) throw new System.ComponentModel.Win32Exception();
        return stickyKeys;

Upvotes: 4

Related Questions