无法调用 SystemParametersInfo
Trouble calling SystemParametersInfo
最近我一直在尝试从托管代码调用 SystemParametersInfo
方法,但没有成功。
问题是,调用方法后,方法returns 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_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;
最近我一直在尝试从托管代码调用 SystemParametersInfo
方法,但没有成功。
问题是,调用方法后,方法returns 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_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;