【发布时间】:2021-08-20 03:42:49
【问题描述】:
我有以下代码:
using System;
using System.Runtime.InteropServices;
public class WindowsFunctions
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static int TicksSinceLastInput()
{
var info = new LASTINPUTINFO();
GetLastInputInfo(ref info);
var lastInputTickCount = info.dwTime;
return (int)lastInputTickCount;
}
}
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
但是,在运行时,info.dwTime 为零。
在 VS2019 IDE 中运行
更新:
我尝试让TicksSinceLastInput 不是静态的,但无论如何都会失败。
我失败的单元测试现在是:
[TestMethod]
public void TestTicksSinceLastInput()
{
var funcs = new WindowsFunctions();
var ticks = funcs.TicksSinceLastInput();
Assert.IsTrue( ticks > 0);
}
更新:
我的代码现在是:
public class WindowsFunctions
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public int TicksSinceLastInput()
{
var info = new LASTINPUTINFO();
var result = GetLastInputInfo(ref info);
var lastInputTickCount = info.dwTime;
return (int)lastInputTickCount;
}
}
结果被设置为假。
【问题讨论】:
-
我没有看到你在初始化
cbSize。你计算它,但我没有看到任何初始化 -
Pinvoke.net 永远是你的朋友:pinvoke.net/default.aspx/user32/GetLastInputInfo.html
-
谢谢各位。我现在可以正常工作了,我没有正确初始化。 PInvoke 中的代码是正确的
标签: c# winforms winapi interop user32