如何知道 Windows 何时启动或关闭?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7407286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:03:58  来源:igfitidea点击:

How to know when was Windows started or shutdown?

c#windows

提问by YAM

I need to develop a program in C# find out when was Windows started or shutdown.

我需要用 C# 开发一个程序,找出 Windows 何时启动或关闭。

Is there a log file that I can read to know Windows start and shutdown times? Or do you have any ideas how to do so?

是否有我可以阅读的日志文件来了解 Windows 启动和关闭时间?或者你有什么想法怎么做?

EDIT :

编辑 :

With the help of Mr. Reed Copsey, the best answer is found under this question.

在 Reed Copsey 先生的帮助下,在这个问题下找到了最佳答案。

采纳答案by Reed Copsey

You can use the classes in System.Diagnostics.Eventing.Readerto access the system Event Logs.

您可以使用System.Diagnostics.Eventing.Reader 中的类来访问系统事件日志。

回答by Uwe Keim

According to this articleyou can use WMI to get the last boot date/time.

根据这篇文章,您可以使用 WMI 获取上次启动日期/时间

// define a select query
SelectQuery query =
    new SelectQuery(@"SELECT LastBootUpTime FROM Win32_OperatingSystem
       WHERE Primary='true'");

// create a new management object searcher and pass it
// the select query
ManagementObjectSearcher searcher =
    new ManagementObjectSearcher(query);

// get the datetime value and set the local boot
// time variable to contain that value
foreach(ManagementObject mo in searcher.Get())
{
    dtBootTime =
        ManagementDateTimeConverter.ToDateTime(
            mo.Properties["LastBootUpTime"].Value.ToString());

    // display the start time and date
    txtDate.Text = dtBootTime.ToLongDateString();
    txtTime.Text = dtBootTime.ToLongTimeString();
}

回答by Matt

As Reed pointed out you could access the Event Logs and see when they were created. AFAIK there are no specific event entries for system startup/shutdown, but you could look for services that are usually started/stopped with Windows. Though using this approach means it won't be 100% accurate, say if it crashes or it's manually started/stopped/restarted. One event I consider is the most accurate is EventLog service start/stop event.

正如 Reed 指出的那样,您可以访问事件日志并查看它们的创建时间。AFAIK 没有系统启动/关闭的特定事件条目,但您可以查找通常由 Windows 启动/停止的服务。虽然使用这种方法意味着它不会是 100% 准确的,比如它是否崩溃或者它是手动启动/停止/重新启动的。我认为最准确的一个事件是 EventLog 服务启动/停止事件。

if (EventLog.Exists("System"))
{
    var log = new EventLog("System", Environment.MachineName, "EventLog");

    var entries = new EventLogEntry[log.Entries.Count];
    log.Entries.CopyTo(entries, 0);

    var startupTimes = entries.Where(x => x.InstanceId == 2147489653).Select(x => x.TimeGenerated);
    var shutdownTimes = entries.Where(x => x.InstanceId == 2147489654).Select(x => x.TimeGenerated);
}

Edit

编辑

Turns out there was a shutdown event. You can replace the Linq to get it:

原来有一个关闭事件。您可以替换 Linq 来获取它:

var shutdownEvents = entries.Where(x => x.InstanceId == 2147484722);

回答by Sravan

Last Restart time can be found using this piece of code

使用这段代码可以找到上次重启时间

static void Main(string[] args)
    {          
        TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
        Console.WriteLine( DateTime.Now.Subtract(t));          
    }

回答by Hans

You could use the "System Up Time" performance counter to get the start time of the system:

您可以使用“System Up Time”性能计数器来获取系统的启动时间:

 PerformanceCounter systemUpTime = new PerformanceCounter("System", "System Up Time");

 systemUpTime.NextValue();
 TimeSpan upTimeSpan = TimeSpan.FromSeconds(systemUpTime.NextValue());
 Console.Out.WriteLine(DateTime.Now.Subtract(upTimeSpan).ToShortTimeString());

Hope, this helps.

希望这可以帮助。

回答by figolu

System.Environment.TickCounthas a 24.8 days limitation.
This is because TickCountis a millisecond value contained in a signed 32 bits value.

System.Environment.TickCount有 24.8 天的限制。
这是因为TickCount是包含在有符号的 32 位值中的毫秒值。

Windows API exposes these two functions:
GetTickCount- returns a 32 bits value - available from Windows 2000
GetTickCount64- returns a 64 bits value - available from Vista/Windows Server 2008

Windows API 公开了这两个函数:
GetTickCount- 返回 32 位值 - 可从 Windows 2000 获得
GetTickCount64- 返回 64 位值 - 可从 Vista/Windows Server 2008 获得

You can use GetTickCount64 this way:

您可以这样使用 GetTickCount64:

using System.Runtime.InteropServices;  

[DllImport("Kernel32.dll")]  
static extern long GetTickCount64();  

DateTime osStartTime = DateTime.Now - new TimeSpan(10000 * GetTickCount64());