无法调用SystemParametersInfo

时间:2015-06-26 17:15:46

标签: c# .net windows winapi pinvoke

最近,我一直试图从托管代码调用SystemParametersInfo方法,但没有任何成功。

问题是,在调用方法之后,该方法返回false(表示失败),但是GetLastError(由Marshal.GetLastWin32Error()检索)是0

我尝试从C ++调用该方法作为测试(具有完全相同的参数),并且从那里完全正常。

方法的P / Invoke声明是这样的:

[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;
}

调用如下:

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

SPI.SPI_GETSTICKYKEYS0x003A(如MSDN所示)。

此处结果为false,返回的错误为0 如果重要的话,这也被编译为64位可执行文件。

我完全在我的智慧结束时,你知道我可能做错了什么吗?

1 个答案:

答案 0 :(得分:4)

正如GSerg向我指出的那样,我的问题是我需要直接将结构的大小作为参数传递,并作为我通过引用传入的结构的cbSize成员。 正确的代码是:

        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;
相关问题