C# 项目06-计算程序运行时间

实现需求

记录程序运行时间,当程序退出后,保存程序运行时间,等下次程序再次启动时,继续记录运行时间

运行环境

Visual Studio 2022

知识点

TimeSpan

表示时间间隔。两个日期之间的差异的 TimeSpan 对象

C# 复制代码
TimeSpan P_TimeSpan;
DateTime G_DateTime = DateTime.Now;
P_TimeSpan = DateTime.Now - G_DateTime;
/*
 P_TimeSpan.Days;时间间隔的天数
 P_TimeSpan.Hours;时间间隔的小时
 P_TimeSpan.Minutes;时间间隔的分钟
 P_TimeSpan.Seconds;时间间隔的分钟
*/

断电保持

本项目用的方法是将数据保存到项目属性中,操作方法如下:

  1. 右键点击项目,然后点击属性

2、在设置中创建对应的变量和数据类型,范围默认为用户

3、利用窗体的FormClosing事件,保存数据

C# 复制代码
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DateTime G_DateTime_Close = DateTime.Now;
            Properties.Settings.Default.RuntimeDays = P_TimeSpan.Days + Properties.Settings.Default.RuntimeDays;
            Properties.Settings.Default.RuntimeHours = P_TimeSpan.Hours + Properties.Settings.Default.RuntimeHours;
            Properties.Settings.Default.RuntimeMinutes = P_TimeSpan.Minutes + Properties.Settings.Default.RuntimeMinutes;
            Properties.Settings.Default.RuntimeSeconds = P_TimeSpan.Seconds + Properties.Settings.Default.RuntimeSeconds;
            Settings.Default.Save();
        }

4、读取数据

C# 复制代码
Properties.Settings.Default.RuntimeDays
Properties.Settings.Default.RuntimeHours
Properties.Settings.Default.RuntimeMinutes
Properties.Settings.Default.RuntimeSeconds

动画演示

相关推荐
阿里嘎多学长40 分钟前
2026-04-30 GitHub 热点项目精选
开发语言·程序员·github·代码托管
叶小鸡2 小时前
Java 篇-项目实战-苍穹外卖-笔记汇总
java·开发语言·笔记
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题】【Java基础篇】第22题:HashMap 和 HashSet 有哪些区别
java·开发语言·哈希算法·散列表·hash
时空系3 小时前
第10篇:继承扩展——面向对象编程进阶 python中文编程
开发语言·python·ai编程
CHANG_THE_WORLD4 小时前
python 批量终止进程exe
开发语言·python
古城小栈4 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
Gary Studio6 小时前
安卓HAL C++基础-智能指针
开发语言·c++
啧不应该啊6 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
cen__y6 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
xingpanvip6 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua