【发布时间】:2023-04-10 07:01:01
【问题描述】:
我一直在使用来自https://github.com/cerebrate/mousejiggler 的一些代码来防止 Windows PC 闲置。它工作正常,但是当我将它移植到一个新应用程序时,它在执行时开始崩溃。具体在这一行:
if (SendInput(1, ref inp, 28) != 1)
throw new Win32Exception();
新应用程序作为 x64 应用程序运行,而旧应用程序是 x86。为 x86 构建新应用程序解决了这个问题。完整代码如下。我正在努力弄清楚为什么会这样。根据平台的不同,strut 中有一个IntPtr 将从 4 字节变为 8 字节,但据我所知,没有办法改变它。我想我可以创建一个 32 位 int 指针并使用不安全的代码,但我什至不确定这是否真的是问题所在。
关于如何为 x64 平台修复它的任何想法?
[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;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
static uint GetLastInputTime()
{
uint idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
uint envTicks = (uint)Environment.TickCount;
if (GetLastInputInfo(ref lastInputInfo))
{
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
public static class Jiggler
{
internal const int INPUT_MOUSE = 0;
internal const int MOUSEEVENTF_MOVE = 0x0001;
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
public static void Jiggle(int dx, int dy)
{
var inp = new INPUT();
inp.TYPE = Jiggler.INPUT_MOUSE;
inp.dx = dx;
inp.dy = dy;
inp.mouseData = 0;
inp.dwFlags = Jiggler.MOUSEEVENTF_MOVE;
inp.time = 0;
inp.dwExtraInfo = (IntPtr)0;
if (SendInput(1, ref inp, 28) != 1)
throw new Win32Exception();
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct INPUT
{
public int TYPE;
public IntPtr dwExtraInfo;
public int dwFlags;
public int dx;
public int dy;
public int mouseData;
public int time;
}
【问题讨论】:
-
“为 x86 构建新应用程序解决了这个问题”... 如果您的程序不需要编译为 64 位,那么您就可以开始了,不是吗?要在 64 位上运行,您很可能需要为 64 位平台编译的 DLL。
-
它不需要以 x64 运行,但由于它使用标准的 Windows dll,如果无法在 x64 应用程序下使用它,我会感到惊讶。