0
1

More than 5 years have passed since last update.

C#終了時処理覚書

Posted at

終了時の処理記述に詰まったので覚書

Appのロード時に処理

FormにLoadのイベントハンドラを追加

    private void Form1_Load(object sender, EventArgs e)
    {
      ///ここに開始時処理を記述///  
    }

Appの終了時に処理

FormにFormClosingのイベントハンドラを追加

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
       ///ここに終了時処理を記述///
    }

 使用例

Formの開始時にtimelog.txtを探し、あれば追記、無ければ作成し、現在時刻を書き込む。終了時にも現在時刻を書き込み、改行する。

timelog.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace hoge
{
    public partial class Form1 : Form
    {       
        //Form開始時の処理
        private void Form1_Load(object sender, EventArgs e)
        {
            //開始時に現在時刻の記録
            DateTime localTime = DateTime.Now;
            File.AppendAllText(@"timelog.txt", localTime+" ", Encoding.UTF8);            
        }

        //Form終了時の処理
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //終了時に現在時刻の記録
            DateTime localTime = DateTime.Now;
            File.AppendAllText(@"timelog.txt", localTime + Environment.NewLine, Encoding.UTF8);
        }
    }
}

timelog.txt

2019/02/28 23:25:55///開始時 2019/02/28 23:25:58///終了時
2019/02/28 23:45:13 2019/02/28 23:45:19
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1