c# - 当我们从任务管理器中的进程选项卡关闭应用程序时如何获取登录.txt

标签 c# .net vb.net

我制作了一个 Windows 应用程序,然后运行它。 然后我从应用程序选项卡的任务管理器中关闭该应用程序,然后单击结束任务按钮。然后我的 .txt 日志已成功创建。 然后他们是任务管理器中另一个名为 PROCESS TAB 的 TAB,但是当我结束该应用程序的进程时,我的日志文件没有创建。

这是我的代码。

    public  bool eventHandled;
    private int elapsedTime;
    public Form1()
    {
        elapsedTime = 0;
        InitializeComponent();
       //From here Log created when we click from application atb
        this.Size = new System.Drawing.Size(300, 300);
            this.Text = "Form1";
            LogWrite("Application Start At :");
    }

  public static void LogWrite(string logMessage){
                   try     {                
       string path = @"D:\oldCode\log.txt";               
        if (!File.Exists(path))                
               {
                File.Create(path);
                TextWriter tw = new StreamWriter(path);
                tw.Close();
            }

            using (StreamWriter w = File.AppendText(path))
            {
                Log(logMessage, w);
            }
        } 
        catch (Exception ex)
        {
        }
    }
    //event handler for termination of a process

    public static void Log(string logMessage, TextWriter txtWriter)
    {
        try
        {
            txtWriter.Write("\r\n"+logMessage);
            txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            //txtWriter.WriteLine("  :");
            //txtWriter.WriteLine("  :{0}", logMessage);
            txtWriter.WriteLine("-------------------------------");
        }
        catch (Exception ex)
        {
        }
    }
     class MyApplicationContext : ApplicationContext {

    private int formCount;
    private Form1 form1;
    private Rectangle form1Position;
    ////private FileStream userData;

    private MyApplicationContext() {
        formCount = 0;

        // Handle the ApplicationExit event to know when the application is exiting.
        Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

        // Create both application forms and handle the Closed event 
        // to know when both forms are closed.
        form1 = new Form1();
        form1.Closed += new EventHandler(OnFormClosed);            
        form1.Closing += new CancelEventHandler(OnFormClosing);
     //   form1.Closing += new CancelEventHandler(onprocesscloase);
        formCount++;


        // Get the form positions based upon the user specific data. 

        form1.Show();

        // this is for PROCESS to kill it
         Process myProcess = new Process();
        myProcess.StartInfo.FileName = "";
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.EnableRaisingEvents = true;
        myProcess.Exited += new EventHandler(myProcesses_Exited);

    }

          //METHOD TO KILL PROCESS
    private void myProcesses_Exited(object sender, EventArgs e)
    {
        //Process ps = (Process) sender;
        //messageBox.Text = ps.ProcessName;
        //messageBox.Text = " has exited";
        //  MessageBox.Show("Exited event caught");
        LogWrite("Application Start At :");
       // myProcess.CloseMainWindow();
    }
    private void OnApplicationExit(object sender, EventArgs e) {
        // When the application is exiting, write the application data to the 
        // user file and close it.

    }
    private void OnFormClosing(object sender, CancelEventArgs e) {
        // When a form is closing, remember the form position so it 
        // can be saved in the user data file. 
        if (sender is Form1) 
            form1Position = ((Form)sender).Bounds;

    }

    private void OnFormClosed(object sender, EventArgs e) {
        // When a form is closed, decrement the count of open forms. 

        // When the count gets to 0, exit the app by calling 
        // ExitThread().
        formCount--;
        if (formCount == 0) {
            LogWrite("Application End At :");
            ExitThread();
        }
    }

    [STAThread]
    static void Main(string[] args) {

        // Create the MyApplicationContext, that derives from ApplicationContext, 
        // that manages when the application should exit.

        MyApplicationContext context = new MyApplicationContext();

        // Run the application with the specific context. It will exit when 
        // all forms are closed.
        Application.Run(context);

    }

}

最佳答案

列夫是正确的。当您从“应用程序”选项卡中单击“结束任务”时,Windows 会向您的应用程序发送一条 WM_CLOSE 消息。这与单击红色 X 关闭按钮或在应用程序的主窗体上调用 Me.Close 相同。发生这种情况时,您的表单关闭事件将被触发,您的应用程序可以正常关闭。

当您单击“进程”选项卡中的“结束进程”按钮时,Windows 只会终止您的进程,并且不会触发任何事件。

您可以通过运行 Spy++ 并让它监视发送到您的应用程序的消息来验证这一点。当您从“进程”选项卡终止应用程序时,您不会看到任何消息发送到您的应用程序。

就像您可以通过单击“开始”>“关机”来关闭 Windows,Windows 将正常关闭,或者您只需从墙上拔下插头,计算机就会立即关闭。

如果应用程序从“进程”选项卡终止,您将无能为力。

关于c# - 当我们从任务管理器中的进程选项卡关闭应用程序时如何获取登录.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035866/

相关文章:

c# - .NET DateTime 会截断我的秒数吗?

.net - 如何查找两个日期/DateTimePicker 之间的天数

c# - 从 VB6 字符串数据到 .NET 字节数组的转换

c# - 如何将 MySql 的返回数据分配给 C# 变量?

c# - 如何以同步方式合并两个 TPL DataFlow 管道?

c# - 提取部分字符串

C# 将 XML 反序列化为对象

c# - 命名 bool 属性的 FDG 是什么?

c# - 如何在C#中创建带有特殊字符的字符串

windows - 如何让下面的 dsf 代码工作?