Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何跟踪pc启动、关闭和关键关闭_C#_Windows - Fatal编程技术网

C# 如何跟踪pc启动、关闭和关键关闭

C# 如何跟踪pc启动、关闭和关键关闭,c#,windows,C#,Windows,我有大约250台笔记本电脑在移动推车上,我知道它们没有被充分利用。我正在编写一个程序,该程序编写一个日志文件来捕获开机和关机事件。但是,当我试图捕获立即关机事件(用户按住电源按钮)时,我不会将数据写入文本文件 任何意见都会有帮助。提前谢谢 代码: 阅读系统的事件日志并查找这些事件发生的时间可能更有意义 或者,如果这不理想,与其监听关机事件,不如连接到程序的终止,假设程序正在关闭,计算机正在关机,并调用其中的Write_数据。请注意,此SO线程中的某些解决方案在Windows7上不起作用,并且在控

我有大约250台笔记本电脑在移动推车上,我知道它们没有被充分利用。我正在编写一个程序,该程序编写一个日志文件来捕获开机和关机事件。但是,当我试图捕获立即关机事件(用户按住电源按钮)时,我不会将数据写入文本文件

任何意见都会有帮助。提前谢谢

代码:


阅读系统的事件日志并查找这些事件发生的时间可能更有意义

或者,如果这不理想,与其监听关机事件,不如连接到程序的终止,假设程序正在关闭,计算机正在关机,并调用其中的Write_数据。请注意,此SO线程中的某些解决方案在Windows7上不起作用,并且在控制台/窗体应用程序关闭时的行为不同

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

    namespace Log
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            string CrLf = System.Environment.NewLine;
            private static int WM_QUERYENDSESSION = 0x11;
            private static int WM_ENDSESSION_CRITICAL = 0x40000000;

            private static bool systemShutdown = false;

            private void Form1_Load(object sender, EventArgs e)
            {
                Write_Data("[" + DateTime.Now.ToString() + "] " + "Power on");            
            }


            protected override void WndProc(ref System.Windows.Forms.Message m)
            {

                if (m.Msg == WM_QUERYENDSESSION)
                {
                    Write_Data("[" + DateTime.Now.ToString() + "] " + "Power off");
                    systemShutdown = true;
                }
                // If this is WM_QUERYENDSESSION, the closing event should be
                // raised in the base WndProc.

                    if (m.Msg == WM_ENDSESSION_CRITICAL)
                    {
                        Write_Data("[" + DateTime.Now.ToString() + "] " + "Critical power down");
                        systemShutdown = true;
                    }

                    base.WndProc(ref m);
            }       

            private void Write_Data(string str_Data)
            {
                using (StreamWriter output = new StreamWriter("../Log.txt", true))
                {
                    output.WriteLine(str_Data);
                }
            }
        }

    }