You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#新手求助:解决无法隐式转换long到uint与未赋值局部变量错误

解决C#中Win32 API调用的两个编译错误

错误1:未赋值的局部变量 'lASTINPUTINFO'

问题出在对象初始化器里调用Marshal.SizeOf<LASTINPUTINFO>(lASTINPUTINFO)时,变量lASTINPUTINFO还没完成初始化,编译器判定它未被赋值。

修复方式:

  • 直接用泛型方法Marshal.SizeOf<LASTINPUTINFO>(),不需要传入实例;或者用typeof(LASTINPUTINFO)作为参数传入Marshal.SizeOf
  • 也可以先声明变量,再单独赋值cbSize

错误2:无法将long隐式转换为uint

Environment.TickCount返回int类型(若使用TickCount64则为long),而LASTINPUTINFO.dwTime是uint类型,两者相减后的结果类型与方法返回的uint不兼容,编译器不允许隐式转换。

修复方式:

  • 显式把计算结果转换为uint,如果用TickCount64,要确保差值为正再转换
  • 优先用Environment.TickCount64避免32位计时溢出问题

修正后的完整代码

using System;
using System.Runtime.InteropServices;

namespace Utilities
{
    internal class Win32
    {
        // 补全缺失的LASTINPUTINFO结构体定义
        [StructLayout(LayoutKind.Sequential)]
        private struct LASTINPUTINFO
        {
            public uint cbSize;
            public uint dwTime;
        }

        public static uint GetIdleTime()
        {
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            // 直接传入类型获取大小,避免使用未初始化的变量
            lastInputInfo.cbSize = (uint)Marshal.SizeOf<LASTINPUTINFO>();
            
            Win32.GetLastInputInfo(ref lastInputInfo);
            
            // 使用TickCount64避免溢出,显式转换为uint
            long currentTick = Environment.TickCount64;
            return (uint)(currentTick - lastInputInfo.dwTime);
        }

        [DllImport("Kernel32.dll", CharSet = CharSet.None, ExactSpelling = false)]
        private static extern uint GetLastError();

        [DllImport("User32.dll", CharSet = CharSet.None, ExactSpelling = false)]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        public static long GetLastInputTime()
        {
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = (uint)Marshal.SizeOf<LASTINPUTINFO>();
            
            Win32.GetLastInputInfo(ref lastInputInfo);
            // 返回最后输入时间的Tick值,转换为long避免溢出
            return lastInputInfo.dwTime;
        }
    }
}

额外说明:原代码缺失LASTINPUTINFO结构体的定义,这是调用GetLastInputInfo必须的,已在修正代码中补全;同时GetLastInputTime方法原代码未完成,也补充了完整逻辑。

内容的提问来源于stack exchange,提问作者dlaksmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:02:11