using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsSleep
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
if(!IsCdrive())
{
MessageBox.Show("実行ファイルはCドライブにおいてください", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// ログを保存するファイルのパスを取得する
string logFilePath = GetLogFilePath();
if(MessageBox.Show("スタンバイ状態にしますか?", "確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
// スタンバイ状態になった時刻を記録する
SaveLogSuspendTime(logFilePath);
// 実際にスタンバイ状態にする
Application.SetSuspendState(PowerState.Suspend, false, false);
// スタンバイから復帰した時刻も記録する
SaveLogTimeReturnSuspend(logFilePath);
}
}
// 実行ファイルはCドライブにあるか?
static bool IsCdrive()
{
string path = Application.ExecutablePath;
path = path.ToUpper();
if(path.IndexOf("C:\\") != -1)
return true;
else
return false;
}
// ログを保存するファイルのパスを取得するメソッド
// 実行ファイルのなかにlogというフォルダを作成しlog.txtというファイルにする
static string GetLogFilePath()
{
string folderPath = Application.StartupPath + "\\log";
if(!System.IO.Directory.Exists(folderPath))
System.IO.Directory.CreateDirectory(folderPath);
string logFilePath = folderPath + "\\log.txt";
return logFilePath;
}
// スリープさせた時刻を保存するメソッド
static void SaveLogSuspendTime(string logFilePath)
{
DateTime dt = DateTime.Now;
string dtString = dt.ToString("yyyy年MM月dd日 HH時mm分ss秒");
string str = dtString + " スリープ";
SaveLog(logFilePath, str);
}
// スリープから復帰した時刻を保存するメソッド
static void SaveLogTimeReturnSuspend(string logFilePath)
{
DateTime dt = DateTime.Now;
string dtString = dt.ToString("yyyy年MM月dd日 HH時mm分ss秒");
string str = dtString + " 復帰";
SaveLog(logFilePath, str);
}
// ファイルが存在しない場合は作成し、すでに存在するなら追記
static void SaveLog(string filePath, string str)
{
System.IO.StreamWriter sw;
if(System.IO.File.Exists(filePath))
sw = new System.IO.StreamWriter(filePath, true); // ファイルがすでに存在するなら追記
else
sw = new System.IO.StreamWriter(filePath); // ファイルが存在しない場合は作成
sw.WriteLine(str);
sw.Close();
}
}
}