cod*_*sed 4 .net c# environment-variables gettickcount c#-4.0
我想知道系统最后一次启动的时间.
Environment.TickCount会起作用,但由于int的限制,它会在48-49天后破坏.
这是我一直在使用的代码:
Environment.TickCount & Int32.MaxValue
有人知道长型返回吗?
我用它来知道系统的空闲时间:
public static int GetIdleTime()
{
    return (Environment.TickCount & Int32.MaxValue)- (int)GetLastInputTime();
}
/// <summary>
/// Get the last input time from the input devices.
/// Exception: 
/// If it cannot get the last input information then it throws an exception with 
/// the appropriate message.
/// </summary>
/// <returns>Last input time in milliseconds.</returns>
public static uint GetLastInputTime()
{
    LastInputInfo lastInPut = new LastInputInfo();
    lastInPut.BlockSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
    if (!GetLastInputInfo(ref lastInPut))
    {
        throw new Exception(GetLastError().ToString());
    }
    return lastInPut.Time;
}
public void BootTime(){    
    SelectQuery query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    foreach (ManagementObject mo in searcher.Get())
    {
        DateTime dtBootTime = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
        Console.WriteLine(dtBootTime.ToString());
    }
}
以下代码检索自系统启动以来的毫秒数(调用unmanged API).我测量了这个互操作操作的性能成本,它与StopWatch()完全相同(但是当然不会检索自系统启动以来的时间).
using System.Runtime.InteropServices;
...
[DllImport("kernel32.dll") ]
public static extern UInt64 GetTickCount64();
...
var tickCount64 = GetTickCount64();
https://msdn.microsoft.com/de-de/library/windows/desktop/ms724411(v=vs.85).aspx
你是正确的,Environment.TickCount大约25天后会溢出,因为返回值是一个32位整数.
但是,TickCount如果您想确定系统上次启动的时间,那么有一种更好的方法.您正在寻找的是系统正常运行时间.有几种不同的方法可以检索它.
最简单的方法是使用PerformanceCounter类(在System.Diagnostics命名空间中),它允许您查询特定的系统性能计数器.请尝试以下代码:
TimeSpan upTime;
using (var pc = new PerformanceCounter("System", "System Up Time"))
{
    pc.NextValue();    //The first call returns 0, so call this twice
    upTime = TimeSpan.FromSeconds(pc.NextValue());
}
Console.WriteLine(upTime.ToString());
或者,您可以通过WMI执行此操作.但看起来stian.net的答案已经涵盖了.
请注意,最后,该性能计数器的名称必须是本地化的,如果你需要支持Windows的国际版本,所以正确的解决方案必须仰望的"系统"和"系统运行时间"的本地化字符串使用PdhLookupPerfNameByIndex,或者你必须确保你正在使用引擎盖下的PdhAddEnglishCounter,仅在Vista或更高版本中支持.更多关于这里.