最近我一直试图从托pipe代码调用SystemParametersInfo
方法,没有任何成功。
问题是,调用该方法后,该方法返回false
(指示失败),但GetLastError
(由Marshal.GetLastWin32Error()
检索)为0
。
我试图从C ++调用方法作为一个testing(具有完全相同的参数),它从那里完全正常工作。
该方法的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_GETSTICKYKEYS
是0x003A
(如MSDN上所示)。
这里的结果是false
,返回的错误是0
。
如果这很重要的话,这也是作为一个64位的可执行文件来编译的。
我完全是在智慧的结尾,你有什么想法,我可能做错了什么?
正如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;