【问题标题】:Trouble calling SystemParametersInfo调用 SystemParametersInfo 时遇到问题
【发布时间】:2015-06-26 17:15:46
【问题描述】:

最近我一直在尝试从托管代码中调用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 位可执行文件。

我完全无能为力了,你知道我做错了什么吗?

【问题讨论】:

  • 不是一个真正的答案,但你看过msdn.microsoft.com/en-us/library/…
  • documentation 说,将此结构的cbSize 成员和uiParam 参数设置为sizeof(STICKYKEYS) 你这样做吗?
  • @Benj 好像没有粘滞键。
  • @GSerg 我正在尝试先读取该值(这就是使用 SPI_GETSTICKYKEY 调用该函数的原因)。 Afaict,在这种情况下,pvParam 应该用作输出参数。 (基本上我正在尝试在 C# 中重新实现这个 sn-p:link
  • @GSerg 是的!我已经设置了 cbSize 参数,它似乎工作正常。在我的辩护中,我已经将结构的大小传递给了函数,所以我没想到我需要传递两次:)。感谢您的帮助!

标签: c# .net windows winapi pinvoke


【解决方案1】:

正如 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多