36【WinForm】WinForm实现日期计算和日期提醒器

简介: 计算当前日期距离今天之前某个日期之间的时间差。

前言


一、计算日期

计算当前日期距离今天之前某个日期之间的时间差。

1、效果

开始运行显示:
在这里插入图片描述

点击图片任意位置:

在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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;

namespace 计算日期
{
    public partial class Form1 : Form
    {
        public bool isClick = false;
        public Form1()
        {
            InitializeComponent();

            //toolTip1控件
            toolTip1.ToolTipTitle = "嘿嘿";
            toolTip1.SetToolTip(this.pictureBox1, "徒弟喜欢她就点一下吧!");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化界面大小
            this.Width = 210;
            this.Height = 303;
            this.MaximumSize = new Size(210, 303);

            //计算日期
            int days = (DateTime.Now - DateTime.Parse("2011-12-19")).Days;
            int day=(DateTime.Parse("2012-5-19")-DateTime.Now).Days;
            int hours=(DateTime.Parse("2012-5-19")-DateTime.Now).Hours;
            int minutes=(DateTime.Parse("2012-5-19")-DateTime.Now).Minutes;
            int seconds=(DateTime.Parse("2012-5-19")-DateTime.Now).Seconds;

            label2.Text = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
            label5.Text = days + "天";
            label6.Text = day + "天" + hours + "时" + minutes + "分" + seconds + "秒";
        }

        //定时器每秒中更新日期
        private void timer1_Tick(object sender, EventArgs e)
        {
            int day = (DateTime.Parse("2012-5-19") - DateTime.Now).Days;
            int hours = (DateTime.Parse("2012-5-19") - DateTime.Now).Hours;
            int minutes = (DateTime.Parse("2012-5-19") - DateTime.Now).Minutes;
            int seconds = (DateTime.Parse("2012-5-19") - DateTime.Now).Seconds;

            label2.Text = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
            label6.Text = day + "天" + hours + "时" + minutes + "分" + seconds + "秒";
        }

        //界面的大小缩放
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (!isClick)
            {
                isClick = true;
                this.MaximumSize = new Size(609, 303);
                this.Width = 609;
                this.Height = 303;        
            }
            else
            {
                isClick = false;
                this.Width = 210;
                this.Height = 303;
                this.MaximumSize = new Size(210, 303);
            }
        }
    }
}

二、日期提醒器

1、效果

在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DataReminderCS
{
    public partial class ReminderForm : Form
    {
        private Dictionary<DateTime, string> _reminderData = new Dictionary<DateTime, string>();

        public ReminderForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 添加按钮
        /// </summary>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            _reminderData[mcDate.SelectionStart] = tbDateContent.Text;
            string dateText = mcDate.SelectionStart.ToShortDateString();
            //没有在lvDateList中找到当天的日程安排,则添加。
            if (lvDateList.FindItemWithText(dateText) == null)
                lvDateList.Items.Add(dateText);
        }

        //日期控件选择日期
        private void mcDate_DateSelected(object sender, DateRangeEventArgs e)
        {
            if (_reminderData.ContainsKey(e.Start))
                tbDateContent.Text = _reminderData[e.Start];
            else
                tbDateContent.Text = string.Empty;
        }

        private void cmsDateList_Opening(object sender, CancelEventArgs e)
        {
            if (lvDateList.SelectedItems.Count == 0)
            {
                e.Cancel = true;
            }
        }

        //右键编辑
        private void tsmiEdit_Click(object sender, EventArgs e)
        {
            mcDate.SelectionStart = DateTime.Parse(this.lvDateList.SelectedItems[0].Text);
            tbDateContent.Text = _reminderData[mcDate.SelectionStart];
        }

        //右键删除
        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Parse(this.lvDateList.SelectedItems[0].Text);

            lvDateList.Items.Remove(this.lvDateList.SelectedItems[0]);
            _reminderData.Remove(dt);
            if (mcDate.SelectionStart == dt)
            {
                tbDateContent.Text = String.Empty;
            }
        }

        /// <summary>
        /// ToolTip提示
        /// </summary>
        private void lvDateList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvDateList.SelectedItems.Count > 0)
            {
                ListViewItem currentItem = lvDateList.SelectedItems[0];
                ttDateContent.ToolTipTitle = currentItem.Text;
                Point showPoint = Point.Add(currentItem.Position, new Size(60, 0));
                ttDateContent.Show(_reminderData[DateTime.Parse(currentItem.Text)], lvDateList, showPoint, 5000);
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        private void ReminderForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!cbAutoSave.Checked)
            {
                return;
            }
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                using(FileStream fs=new FileStream("Data.dat",FileMode.Create))
                {
                    bf.Serialize(fs, _reminderData);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        private void ReminderForm_Load(object sender, EventArgs e)
        {
            if (File.Exists("Data.dat"))
            {
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    using (FileStream fs = new FileStream("Data.dat", FileMode.Open))
                    {
                         _reminderData = (Dictionary<DateTime, string>)bf.Deserialize(fs);
                    }

                    foreach (DateTime dt in _reminderData.Keys)
                    {
                        lvDateList.Items.Add(dt.ToShortDateString());
                    }
                    if (_reminderData.ContainsKey(mcDate.SelectionStart))
                    {
                        tbDateContent.Text = _reminderData[DateTime.Parse(mcDate.SelectionStart.ToShortDateString())];
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="data">要验证的字符串</param>
        /// <returns></returns>
        private bool ValidateFormat(string data)
        {
            int timeSplitIndex = data.IndexOf('-');
            int dateSplitIndex = data.IndexOf(' ');

            //如果没有空格或-,则认为格式不合法。
            if (timeSplitIndex == -1 || dateSplitIndex == -1)
                return false;

            //尝试将时间转化为DateTime类型
            try
            {
                string startTime = data.Substring(0, timeSplitIndex);
                string endTime = data.Substring(timeSplitIndex + 1, dateSplitIndex - timeSplitIndex - 1);

                DateTime startDateTime = DateTime.Parse(startTime);
                DateTime endDateTime = DateTime.Parse(endTime);

                //转化为DateTime类型时,日期为程序运行时的日期。
                //此处判断防止用户自定义日期。
                if (startDateTime.Date == DateTime.Today && endDateTime.Date == DateTime.Today)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 文本框的验证事件
        /// </summary>
        private void tbDateContent_Validating(object sender, CancelEventArgs e)
        {
            int lineIndex = 0;
            foreach (string line in tbDateContent.Lines)
            {
                lineIndex++;
                if(line!=null && line.Trim()!=string.Empty && !ValidateFormat(line))
                {
                    e.Cancel = true;
                    break;
                }
            }

            if (e.Cancel)
            {
                epContent.SetError(label1, string.Format("第{0}行验证出现错误!详情按F1", lineIndex));
            }
            else
            {
                epContent.Clear();
            }
        }

        /// <summary>
        /// timer事件
        /// </summary>
        private void tmrReminder_Tick(object sender, EventArgs e)
        {
            //在lvDateList中的且开启了提醒功能,才进行提示。
            ListViewItem lvi = lvDateList.FindItemWithText(DateTime.Now.ToShortDateString());
            if (lvi == null || !lvi.Checked)
                return;

            Queue<string> reminderMessage = new Queue<string>();

            string reminderData = _reminderData[DateTime.Today];
            string[] dataArray = reminderData.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            foreach (string data in dataArray)
            {
                //此处假设所有数据的格式均合法。
                int timeSplitIndex = data.IndexOf('-');
                int dateSplitIndex = data.IndexOf(' ');

                string startTime = data.Substring(0, timeSplitIndex);
                string date = data.Substring(dateSplitIndex + 1);
                DateTime startDateTime = DateTime.Parse(startTime);

                if (startDateTime.Hour == DateTime.Now.Hour && startDateTime.Minute == DateTime.Now.Minute)
                    reminderMessage.Enqueue(date);
            }

            while (reminderMessage.Count > 0)
            {
                MessageBox.Show("您的日程安排已到期:" + reminderMessage.Dequeue(), "日程安排提示窗口");
            }
        }

        private void lvDateList_ItemDrag(object sender, ItemDragEventArgs e)
        {
            lvDateList.DoDragDrop(e.Item, DragDropEffects.Copy);
        }

        private void tbDateContent_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void tbDateContent_DragDrop(object sender, DragEventArgs e)
        {
            ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            DateTime dt = DateTime.Parse(lvi.Text);
            mcDate.SelectionStart = dt;
            tbDateContent.Text = _reminderData[dt];
        }
    }
}

总结

目录
相关文章
|
Java 数据库连接 数据库
Mybatis-plus中的QueryWrapper的多种用法!(总结)
Mybatis-plus中的QueryWrapper的多种用法!(总结)
3231 0
|
C# 索引 Windows
Winform控件优化之TabControl控件的使用和常用功能
TabControl是一个分页切换(tab)控件,不同的页框内可以呈现不同的内容,将主要介绍调整tab的左右侧显示、设置多行tab、禁用或删除tabpage、隐藏TabControl头部的选项卡等
8404 0
Winform控件优化之TabControl控件的使用和常用功能
|
Java 数据库
Springboot 根据数据库表自动生成实体类和Mapper,只需三步
Springboot 根据数据库表自动生成实体类和Mapper,只需三步
8547 3
Springboot 根据数据库表自动生成实体类和Mapper,只需三步
|
分布式计算 Hadoop API
NoClassDefFoundError - hadoop/crypto/key/KeyProviderTokenIssuer && hadoop/fs/BatchListingOperations
NoClassDefFoundError - hadoop/crypto/key/KeyProviderTokenIssuer && hadoop/fs/BatchListingOperations 报错解决与总结。
813 0
NoClassDefFoundError - hadoop/crypto/key/KeyProviderTokenIssuer && hadoop/fs/BatchListingOperations
|
安全 C# 开发者
Windows Forms 应用开发:一分钟浅谈
本文将带领您从零开始,逐步掌握使用 C# 进行 Windows Forms 开发的技巧,包括创建首个应用、处理常见问题及优化方法。首先介绍如何搭建环境并编写基础代码,接着深入探讨控件使用与布局管理,解决控件重叠和响应式布局难题。最后讲解事件处理与多线程技术,确保长时间任务不阻塞界面,并安全更新 UI 状态,助您开发流畅的应用程序。
634 63
|
机器学习/深度学习 存储 人工智能
【AI系统】轻量级CNN模型综述
本文介绍了几种常见的小型化CNN模型,包括SqueezeNet、ShuffleNet、MobileNet等系列。这些模型通过减少参数量和计算量,实现在有限资源下高效运行,适用于存储和算力受限的场景。文章详细解释了各模型的核心技术和优化策略,如Fire Module、Channel Shuffle、Depthwise Separable Convolutions等,旨在帮助读者理解和应用这些高效的小型化CNN模型。
1232 3
|
Java 数据库连接 Spring
如何在IDEA中自定义模板、快速生成完整的代码?
这篇文章介绍了如何在IntelliJ IDEA中使用easycode插件自定义代码生成模板,以快速生成Spring Boot、MyBatis等项目中常见的Controller、Service、Dao、Mapper等组件的代码。
如何在IDEA中自定义模板、快速生成完整的代码?
|
移动开发 JavaScript 前端开发
UniApp H5 跨域代理配置并使用(配置manifest.json、vue.config.js)
这篇文章介绍了在UniApp H5项目中处理跨域问题的两种方法:通过修改manifest.json文件配置h5设置,或在项目根目录创建vue.config.js文件进行代理配置,并提供了具体的配置代码示例。
UniApp H5 跨域代理配置并使用(配置manifest.json、vue.config.js)
|
存储 编译器 C语言
STM32的启动过程 — startup_xxxx.s文件解析(MDK和GCC双环境)
无论是是何种MCU,从简单的51,MSP430,到ARM9,ARM11,A7 都必须有启动文件,对于MCU来说,他是如何找到并执行main函数的,就需要用到“启动文件”,本文就来说说 STM32 的启动过程。
2040 1
STM32的启动过程 — startup_xxxx.s文件解析(MDK和GCC双环境)
|
数据库 Windows
超详细步骤解析:从零开始,手把手教你使用 Visual Studio 打造你的第一个 Windows Forms 应用程序,菜鸟也能轻松上手的编程入门指南来了!
【8月更文挑战第31天】创建你的第一个Windows Forms (WinForms) 应用程序是一个激动人心的过程,尤其适合编程新手。本指南将带你逐步完成一个简单WinForms 应用的开发。首先,在Visual Studio 中创建一个“Windows Forms App (.NET)”项目,命名为“我的第一个WinForms 应用”。接着,在空白窗体中添加一个按钮和一个标签控件,并设置按钮文本为“点击我”。然后,为按钮添加点击事件处理程序`button1_Click`,实现点击按钮后更新标签文本为“你好,你刚刚点击了按钮!”。
1742 0

热门文章

最新文章