在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C#定时提醒休息小工具源码(可自动显示桌面和动画)

C#定时提醒休息小工具源码(可自动显示桌面和动画)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:1.88M
  • 下载次数:35
  • 浏览次数:460
  • 发布时间:2019-08-21
  • 实例类别:C#语言基础
  • 发 布 人:robot666
  • 文件格式:.zip
  • 所需积分:2
 相关标签:

实例介绍

【实例简介】定时休息,自动显示桌面和动画。 提供C#源代码。

【实例截图】

from clipboard


到了指定休息的时间会弹出如下动画效果:
from clipboard

【核心代码】


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace ShowDesktop
{
    delegate void SetVisible(bool visible);
    delegate void SetNotifyText(string text);
    public partial class AnimForm : Form
    {
        private Image m_imgImage = null;
        private EventHandler m_evthdlAnimator = null;
        System.Threading.Thread ShowThread = null;

        int nStep = 15;
        int nRest = 1;
        int nPause = 60;
        bool bPause = false;
        bool bShowDesktop = true;
        bool bShowAnim = true;
        bool bClosing = false;
        bool bAutoRun = false;

        public AnimForm()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            m_evthdlAnimator = new EventHandler(OnImageAnimate);

            this.Visible = false;
            this.TopMost = true;
            this.WindowState = FormWindowState.Minimized;

            ReadIniFile();

            ShowThread = new System.Threading.Thread(new System.Threading.ThreadStart(ShowDesktopThread));
            ShowThread.Name = "ShowDesktopThread";
            ShowThread.Start();
        }

        private void SetVisible(bool visible)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.InvokeRequired)
            {
                SetVisible d = new SetVisible(SetVisible);
                this.Invoke(d, new object[] { visible });
            }
            else
            {
                if (visible)
                    this.WindowState = FormWindowState.Normal;
                this.Visible = visible;
            }
        }

        private void SetNotifyText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.InvokeRequired)
            {
                SetNotifyText d = new SetNotifyText(SetNotifyText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                notifyIcon1.Text = text;
            }
        }

        private void ShowDesktopThread()
        {
            int nTickLast = System.Environment.TickCount;
            bool bLastPauseChecked = this.bPause;
            bool bLastFullScreenApp = false;
            while (true)
            {
                //有全屏程序运行
                if (RunningFullScreenApp)
                {
                    bLastFullScreenApp = true;
                    System.Threading.Thread.Sleep(100);
                    continue;
                }

                int nTickNow = System.Environment.TickCount;
                //更改暂停状态,重新计时
                if (bLastPauseChecked != this.bPause)
                {
                    bLastPauseChecked = this.bPause;
                    nTickLast = nTickNow;
                }
                //从全屏状态退出,重新计时
                if (bLastFullScreenApp == true)
                {
                    bLastFullScreenApp = false;
                    nTickLast = nTickNow;
                }

                int nRemain = nStep * 60 * 1000;
                //加上暂停的时间
                if (this.bPause)
                {
                    nRemain  = nPause * 60 * 1000;
                }
                nRemain -= nTickNow - nTickLast;
                int nMinute = nRemain /( 60 * 1000);
                int nSecond = nRemain / 1000 - nMinute * 60;
                string text = string.Format("还剩{0}分钟{1}秒休息…", nMinute, nSecond) ;
                SetNotifyText(text);

                //暂停时间结束,开始倒计时下次休息
                if (this.bPause && nTickNow - nTickLast > nPause * 60 * 1000)
                {
                    this.bPause = false;
                    nTickLast = nTickNow;
                }
                //开始休息
                else if (!this.bPause && nTickNow - nTickLast > nStep * 60 * 1000)
                //if (nRemain <= 0)
                {
                    if (this.bPause) this.bPause = false;
                    nTickLast = nTickNow;
                    if (bShowDesktop)//显示桌面
                        ShowDesktop();
                    System.Threading.Thread.Sleep(100);
                    if (bShowAnim)//显示动画
                        SetVisible(true);
                }
                //结束休息
                else if (!this.bPause && nTickNow - nTickLast > nRest * 60 * 1000)
                //else if (nTickNow - nTickLast > nRest * 60 * 1000)
                {
                    SetVisible(false);
                }
                System.Threading.Thread.Sleep(100);
            }
        }

        void ShowDesktop()
        {
            Type oleType = Type.GetTypeFromProgID("Shell.Application");
            object oleObject = System.Activator.CreateInstance(oleType);
            oleType.InvokeMember("ToggleDesktop", BindingFlags.InvokeMethod, null, oleObject, null);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (m_imgImage != null)
            {
                UpdateImage();
                // 绘制图片的当前帧
                e.Graphics.DrawImage(m_imgImage, new Rectangle(0, 0, m_imgImage.Width, m_imgImage.Height));
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                Stream manifestResourceStream = this.GetType().Assembly.GetManifestResourceStream("ShowDesktop.amtf.gif");
                m_imgImage = Image.FromStream(manifestResourceStream, true);
            }
            catch
            {
                MessageBox.Show("无法载入动画文件!", "ShowDesktop");
                MyClose();
            }
            BeginAnimate();
        }
        #region functions of animator image
        private void BeginAnimate()
        {
            if (m_imgImage == null)
                return;

            if (ImageAnimator.CanAnimate(m_imgImage))
            {
                ImageAnimator.Animate(m_imgImage, m_evthdlAnimator);
            }
        }

        private void StopAnimate()
        {
            if (m_imgImage == null)
                return;

            if (ImageAnimator.CanAnimate(m_imgImage))
            {
                ImageAnimator.StopAnimate(m_imgImage, m_evthdlAnimator);
            }
        }

        private void UpdateImage()
        {
            if (m_imgImage == null)
                return;

            if (ImageAnimator.CanAnimate(m_imgImage))
            {
                ImageAnimator.UpdateFrames(m_imgImage);
            }
        }

        /// <summary>
        /// 动画图片帧变化的时间触发,这个事件并非在主线程中触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnImageAnimate(Object sender, EventArgs e)
        {
            this.Invalidate();
        }
        #endregion // End of functions of animator image

        private void AnimForm_Paint(object sender, PaintEventArgs e)
        {
            System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
            shape.AddEllipse(50, 60, 423, 438);
            this.Region = new Region(shape);
        }

        private void AnimForm_MouseDown(object sender, MouseEventArgs e)
        {
            this.Visible = false;
        }

        public SetForm form = null;

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (form == null)
            {
                form = new SetForm(SetParam, MyClose, nStep, nRest, bPause, nPause, bShowDesktop, bShowAnim, bAutoRun);
                form.Show();
            }
            else
            {
                form.Visible = true;
                form.WindowState = FormWindowState.Normal;
            }
        }

        private void ReadIniFile()
        {
            try
            {
                using (StreamReader reader = File.OpenText("ShowDesktop.ini"))
                {
                    string line = "";
                    string[] values;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.StartsWith("RestStep"))
                        {
                            values = line.Split(' ');
                            nStep = Convert.ToInt32(values[values.Length - 1]);
                            nStep = nStep <= 0 ? 1 : nStep;
                        }
                        else if (line.StartsWith("RestTime"))
                        {
                            values = line.Split(' ');
                            nRest = Convert.ToInt32(values[values.Length - 1]);
                            nRest = nRest <= 0 ? 1 : nRest;
                        }
                        else if (line.StartsWith("PauseTime"))
                        {
                            values = line.Split(' ');
                            nPause = Convert.ToInt32(values[values.Length - 1]);
                            nPause = nPause <= 0 ? 1 : nPause;
                        }
                        else if (line.StartsWith("ShowDesktop"))
                        {
                            values = line.Split(' ');
                            bShowDesktop = Convert.ToBoolean(values[values.Length - 1]);
                        }
                        else if (line.StartsWith("ShowAnim"))
                        {
                            values = line.Split(' ');
                            bShowAnim = Convert.ToBoolean(values[values.Length - 1]);
                        }
                        else if (line.StartsWith("AutoRun"))
                        {
                            //读配置文件不顶事!
                            //values = line.Split(' ');
                            //bAutoRun = Convert.ToBoolean(values[values.Length - 1]);
                        }
                    }
                    reader.Close();
                    if (!bShowDesktop && !bShowAnim)
                        bShowDesktop = true;
                    bAutoRun = IsAutoRun();//还是注册表说了算呀
                }
            }
            catch
            {
            }
        }
        private void WriteIniFile()
        {
            try
            {
                using (StreamWriter writer = File.CreateText("ShowDesktop.ini"))
                {
                    string line = string.Format("RestStep {0}", nStep);
                    writer.WriteLine(line);
                    line = string.Format("RestTime {0}", nRest);
                    writer.WriteLine(line);
                    line = string.Format("PauseTime {0}", nPause);
                    writer.WriteLine(line);
                    line = string.Format("ShowDesktop {0}", bShowDesktop);
                    writer.WriteLine(line);
                    line = string.Format("ShowAnim {0}", bShowAnim);
                    writer.WriteLine(line);
                    line = string.Format("AutoRun {0}", bAutoRun);
                    writer.WriteLine(line);
                    writer.Close();
                }
            }
            catch
            {
            }
        }

        public void SetParam(int nStep, int nRest, bool bPause, int nPause, bool bShowDesktop, bool bShowAnim, bool bAutoRun)
        {
            form = null;
            this.nStep = nStep;
            this.nRest = nRest;
            this.bPause = bPause;
            this.nPause = nPause;
            this.bShowDesktop = bShowDesktop;
            this.bShowAnim = bShowAnim;
            this.bAutoRun = bAutoRun;
            if (bAutoRun != IsAutoRun())
            {
                SetAutoRun(this.GetType().Assembly.Location, bAutoRun);
                //有时候写不成功的,所以要再读一遍真正的数值。
                this.bAutoRun = IsAutoRun();
            }
            WriteIniFile();
        }

        private bool IsAutoRun()
        {
            RegistryKey reg = null;
            try
            {
                string fileName = this.GetType().Assembly.Location;
                String name = fileName.Substring(fileName.LastIndexOf(@"/")   1);
                name = name.Substring(fileName.LastIndexOf(@"\")   1);
                reg = OpenRegistryPath(Registry.CurrentUser, @"/SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
                string value = reg.GetValue(name).ToString();
                return string.Equals(fileName, value);
            }
            catch
            {
                MessageBox.Show("无法读注册表,不能判断当前是否是开机自动运行。", "ShowDesktop");
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
            return false;
        }

        private void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            try
            {
                String name = fileName.Substring(fileName.LastIndexOf(@"/")   1);
                name = name.Substring(fileName.LastIndexOf(@"\")   1);
                reg = OpenRegistryPath(Registry.CurrentUser, @"/SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
                if (reg == null)
                    throw new Exception();
                if (isAutoRun)
                    reg.SetValue(name, fileName);
                else
                    reg.SetValue(name, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("尝试设置开机自动运行,写入系统注册表失败!\r\n请尝试关闭关闭第三方防护软件,\r\n或者关闭本程序,尝试以管理员身份再次运行。", "ShowDesktop");
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

        private RegistryKey OpenRegistryPath(RegistryKey root, string s)
        {
            s = s.Remove(0, 1)   @"/";
            while (s.IndexOf(@"/") != -1)
            {
                //root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));
                root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")), true);
                s = s.Remove(0, s.IndexOf(@"/")   1);
            }
            return root;
        }

        public void MyClose()
        {
            ShowThread.Abort();
            this.RegisterAppBar(true);
            bClosing = true;
            if (m_imgImage != null)
            {
                StopAnimate();
                m_imgImage = null;
            }
            this.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (!bClosing)
            {
                this.Visible = false;
                e.Cancel = true;
            }
            return;
        }
    } 
 }


标签:

实例下载地址

C#定时提醒休息小工具源码(可自动显示桌面和动画)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警