1. 程式人生 > >C# 定時關機小應用

C# 定時關機小應用

C# 定時關機小應用(Winform)

一、簡述

     記--使用winform實現的定時關機小應用。通過執行cmd命令實現的。(Visual Studio 2010旗艦版)

     例子打包:連結: https://pan.baidu.com/s/17cVw_nzo2QPqmHwIHK57Ww 提取碼: shzm 

二、效果

            

            

三、工程結構及佈局檢視

 

四、原始檔

Form1.cs檔案

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;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace SetTime1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            lblNow.BackColor = Color.Gainsboro;
        }
        /// <summary>
        /// 窗體載入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            try
            {
                //顯示當前時間
                lblNow.Text = DateTime.Now.ToString("yyyy年MM月dd日hh時mm分ss秒");
                Timer timer = new Timer();
                timer.Tick += new EventHandler(this.timer_Tick);
                timer.Enabled = true;

                //不斷捕獲滑鼠位置
                Timer timer1 = new Timer();
                timer1.Tick += new EventHandler(this.timer1_Tick);
                timer1.Enabled = true;

                //初始化模式一
                InitialModel1();

                //初始化重啟模式
                InitialRset();

                //初始化模式2
                InitialModel2();
            }
            catch { }

        }
        /// <summary>
        /// 當前時間
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)//當前時間
        {
            try
            {
                //在標籤上實時顯示當前時間
                lblNow.Text = DateTime.Now.ToString("yyyy年MM月dd日HH時mm分ss秒");
            }
            catch{}
        }
        /// <summary>
        /// 窗體貼邊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)//窗體貼邊
        {
            try
            {
                int ScreenWidth = Screen.PrimaryScreen.WorkingArea.Width;  //獲取螢幕寬度 
                int ScreenRight = Screen.PrimaryScreen.WorkingArea.Right; //獲取螢幕高度 
                System.Drawing.Point mouse_pos = new Point(Cursor.Position.X, Cursor.Position.Y);//獲取滑鼠在螢幕的座標點
                Rectangle Rects = new Rectangle(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height);//儲存當前窗體在螢幕的所在區域
                
                if ((this.Top < 0) && Win32API.PtInRect(ref Rects, mouse_pos))//當滑鼠在當前窗體內,並且窗體的Top屬性小於0
                {//如果窗體已經上貼邊了並且滑鼠在窗體內部,上貼邊展開
                    this.Top = 0;//設定窗體的Top屬性為0
                }
                else if (this.Top > -5 && this.Top < 5 && !(Win32API.PtInRect(ref Rects, mouse_pos)))
                {//當窗體的上邊框與螢幕的頂端的距離小於5,並且滑鼠不在窗體內部時
                         this.Top = 5 - this.Height;//將窗體隱藏到螢幕的頂端,即上貼邊
                }
                
                if ((this.Left >= ScreenWidth - 5) && Win32API.PtInRect(ref Rects, mouse_pos))//當滑鼠在當前窗體內,並且窗體的Left屬性小於ScreenWidth
                {//如果窗體已經右貼邊了並且滑鼠在窗體內部,右貼邊展開
                    this.Left = ScreenWidth - this.Width;//設定窗體的Left屬性為ScreenWidth
                }
                else if (this.Right >= ScreenWidth && !(Win32API.PtInRect(ref Rects, mouse_pos)))
                {//當窗體的右邊框與螢幕的右端的距離小於+5時,並且滑鼠不在窗體內部,右貼邊
                    this.Left = ScreenWidth - 5;//將窗體隱藏到螢幕的右端
                }
            }
            catch { }
        }
        #region 無邊框窗體拖動
        //-------------------無邊框窗體拖動---------------------------  
        Point mouseOff;//滑鼠移動位置變數  
        bool leftFlag;//標誌左鍵是否按下
 
        //滑鼠按下
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {
                    mouseOff = new Point(-e.X, -e.Y); //記下滑鼠移動的偏移量
                    leftFlag = true;                  //點選左鍵按下時標註為true;  
                }
            }
            catch { }
        }
        //滑鼠移動
        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (leftFlag)
                {
                    Point mouseSet = Control.MousePosition;//獲取滑鼠的位置
                    mouseSet.Offset(mouseOff.X, mouseOff.Y);  //設定移動後的位置  
                    this.Location = mouseSet;//設定當前窗體的位置
                }
            }
            catch { }
        }
        //釋放滑鼠
        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                leftFlag = false;//釋放滑鼠後標註為false;  
            }
        }

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            try
            {
                ReleaseCapture();
                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            }
            catch { }
        }

        //------------------------end 無邊框窗體拖動-----------------------------------  
        #endregion
        /// <summary>
        /// 關閉視窗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }//關閉視窗
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMin_Click(object sender, EventArgs e)//最小化
        {
            //將窗體最小化
            this.WindowState = FormWindowState.Minimized;
        }
        /// <summary>
        /// 初始化模式1
        /// </summary>
        void InitialModel1()//初始化模式1
        {
            try
            {
                int item = 0;
                //在小時下拉框新增(0~12)選項
                while (item <= 12)
                {
                    cbbHours1.Items.Add(item);
                    cbbHours1.SelectedIndex = 0;
                    item++;
                }
                //在分鐘下拉框新增(0~59)選項
                for (item = 0; item <= 0x3b; item++)
                {
                    cbbMins1.Items.Add(item);
                    cbbMins1.SelectedIndex = 0;
                }
                //在秒下拉框新增(0~59)選項
                for (item = 0; item <= 0x3b; item++)
                {
                    cbbSeconds1.Items.Add(item);
                    cbbSeconds1.SelectedIndex = 0;
                }
            }
            catch { }

        }
        /// <summary>
        /// 命令函式 (通過黑視窗執行命令)
        /// </summary>
        /// <param name="str">命令</param>
        private void Cmd(string str)//命令函式
        {
            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "cmd.exe";//呼叫cmd.exe程式
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardInput = true;//重定向標準輸入
                    process.StartInfo.RedirectStandardOutput = true;//重定向標準輸出
                    process.StartInfo.RedirectStandardError = true;//重定向標準出錯
                    process.StartInfo.CreateNoWindow = true;//不顯示黑視窗
                    process.Start();//開始呼叫執行
                    process.StandardInput.WriteLine(str + "&exit");//標準輸入str + "&exit",相等於在cmd黑視窗輸入str + "&exit"
                    process.StandardInput.AutoFlush = true;//重新整理緩衝流,執行緩衝區的命令,相當於輸入命令之後回車執行
                    process.WaitForExit();//等待退出
                    process.Close();//關閉程序
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 模式1確定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure1_Click(object sender, EventArgs e)//模式1確定
        {
            try
            {
                string strHour = cbbHours1.Items[cbbHours1.SelectedIndex].ToString();//小時
                string strMin = cbbMins1.Items[cbbMins1.SelectedIndex].ToString();//分鐘
                string strSec = cbbSeconds1.Items[cbbSeconds1.SelectedIndex].ToString();//秒數
                if (((cbbHours1.SelectedIndex != 0) || (cbbMins1.SelectedIndex != 0)) || (cbbSeconds1.SelectedIndex != 0))
                {
                    this.Cmd("shutdown -a");//取消之前的關機任務
                    //組織關機命令
                    string strCmd = "shutdown -s -t " + (((((Convert.ToInt32(strHour) * 60) * 60) + (Convert.ToInt32(strMin) * 60)) + Convert.ToInt32(strSec))).ToString();
                    this.Cmd(strCmd);//呼叫cmd執行命令
                    //彈出訊息框告知使用者
                    MessageBox.Show("計算機將在" + strHour + "小時" + strMin + "分" + strSec + "秒後關機");
                }
                else
                {
                    MessageBox.Show("選擇無效!");
                }
            }
            catch { }

        }
        /// <summary>
        /// 取消關機計劃
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel1_Click(object sender, EventArgs e)//取消關機計劃
        {
            this.Cmd("shutdown -a");//呼叫cmd執行取消關機命令
        }
        /// <summary>
        /// 重啟模式
        /// </summary>
        void InitialRset()//初始化重啟模式
        {
            try
            {
                int item = 0;
                //在小時下拉框新增(0~12)選項
                while (item <= 12)
                {
                    cbbHoursRset.Items.Add(item);
                    cbbHoursRset.SelectedIndex = 0;
                    item++;
                }
                //在分鐘下拉框新增(0~59)選項
                for (item = 0; item <= 0x3b; item++)
                {
                    cbbMinsRset.Items.Add(item);
                    cbbMinsRset.SelectedIndex = 0;
                }
                //在秒下拉框新增(0~59)選項
                for (item = 0; item <= 0x3b; item++)
                {
                    cbbSecondsRset.Items.Add(item);
                    cbbSecondsRset.SelectedIndex = 0;
                }
            }
            catch { }

        }


        /// <summary>
        /// 確認重啟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSureRset_Click(object sender, EventArgs e)//重啟模式
        {
            try
            {
                //獲取使用者選擇的時間
                string strHour = cbbHoursRset.Items[cbbHoursRset.SelectedIndex].ToString();//小時
                string strMin = cbbMinsRset.Items[cbbMinsRset.SelectedIndex].ToString();//分鐘
                string strSec = cbbSecondsRset.Items[cbbSecondsRset.SelectedIndex].ToString();//秒

                this.Cmd("shutdown -a");//取消之前的關機任務
                //根據使用者的選擇組織關機命令
                string strCmd = "shutdown -r -t " + (((((Convert.ToInt32(strHour) * 60) * 60) + (Convert.ToInt32(strMin) * 60)) + Convert.ToInt32(strSec))).ToString();
                this.Cmd(strCmd);//呼叫cmd執行重啟命令
                //彈出訊息框告知使用者
                MessageBox.Show("計算機將在" + strHour + "小時" + strMin + "分" + strSec + "秒後重啟");
            }
            catch { }

        }
        /// <summary>
        /// 取消重啟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCancelRset_Click(object sender, EventArgs e)//取消重啟
        {
            this.Cmd("shutdown -a");//取消關機任務
        }

        /// <summary>
        /// 初始化模式2
        /// </summary>
        void InitialModel2()//初始化模式2
        {
            try
            {
                int num;
                this.cbbMonths.Items.Clear();//清空月份下拉框
                //在月份下拉框新增1~12
                for (num = 1; num <= 12; num++)
                {
                    cbbMonths.Items.Add(num);

                }
                //預設選擇當前月
                cbbMonths.SelectedIndex = DateTime.Now.Month - 1;

                this.cbbHours2.Items.Clear();//清空小時下拉框
                //在小時下拉框新增0~23
                for (num = 0; num <= 0x17; num++)
                {
                    this.cbbHours2.Items.Add(num);

                }

                //預設選擇當前小時
                cbbHours2.SelectedIndex = DateTime.Now.Hour;

                this.cbbMins2.Items.Clear();//清空分鐘下拉框、
                //在月份下拉框新增0~59
                for (num = 0; num <= 0x3b; num++)
                {
                    this.cbbMins2.Items.Add(num);

                }
                //預設選擇當前秒
                cbbMins2.SelectedIndex = DateTime.Now.Minute;
                SetDay();//根據使用者選擇的月份選擇天數(月份的天數有差異,有潤平年之分)
            }
            catch { }

        }

        /// <summary>
        /// 設定模式2天數
        /// </summary>
        void SetDay()//設定模式2天數
        {
            try
            {
                int num;
                this.cbbDays.Items.Clear();//清空天數下拉框
                switch ((cbbMonths.SelectedIndex + 1))
                {
                    case 1://1 3 5 7 8 10 12 月有31天
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12: for (num = 1; num <= 31; num++)
                        {
                            cbbDays.Items.Add(num);

                        }
                        break;
                    case 4://4 6 9 11月有30天
                    case 6:
                    case 9:
                    case 11: for (num = 1; num <= 30; num++)
                        {
                            cbbDays.Items.Add(num);

                        }
                        break;
                    case 2: for (num = 1; num <= 28; num++)//2月至少有28天
                        {
                            cbbDays.Items.Add(num);

                        }

                        //閏年 2月 有29天
                        if (((Convert.ToInt32(DateTime.Now.Year) % 400) == 0) || (((Convert.ToInt32(DateTime.Now.Year) % 4) == 0) && ((Convert.ToInt32(DateTime.Now.Year) % 100) != 0)))
                        {
                            cbbDays.Items.Add(0x1d);//再加1天
                        }
                        break;
                    default: break;
                }

                if (Convert.ToInt32(DateTime.Now.Day) > cbbDays.Items.Count)
                {//當前天數大於可選天數,設定為27
                    cbbDays.SelectedIndex = 27;
                }
                else
                {
                    //預設選為當前天數
                    cbbDays.SelectedIndex = Convert.ToInt32(DateTime.Now.Day) - 1;
                }
            }
            catch { }
        }
        /// <summary>
        /// 當月數改變天數隨之改變
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbMonths_SelectedIndexChanged(object sender, EventArgs e)//當月數改變天數隨之改變
        {
            SetDay();
        }
        /// <summary>
        /// 獲取設定模式2關機時間
        /// </summary>
        /// <returns>設定模式2關機時間</returns>
        private DateTime GetDTime()//獲取設定模式2關機時間
        {
            try
            {
                string strYear = Convert.ToString(DateTime.Now.Year);
                string strMouth = this.cbbMonths.Items[this.cbbMonths.SelectedIndex].ToString();
                string strDay = this.cbbDays.Items[this.cbbDays.SelectedIndex].ToString();
                string strHour = this.cbbHours2.Items[this.cbbHours2.SelectedIndex].ToString();
                string strMin = this.cbbMins2.Items[this.cbbMins2.SelectedIndex].ToString();
                //跨年處理
                if ((DateTime.Now.Month == 12) && (this.cbbMonths.SelectedIndex == 0))
                {
                    strYear = (DateTime.Now.Year + 1).ToString();
                }
                //返回設定的時間
                return Convert.ToDateTime(strYear + "-" + strMouth + "-" + strDay + " " + strHour + ":" + strMin + ":00");
            }
            catch
            {
                return DateTime.Now;//返回當前時間
            }

        }
        /// <summary>
        /// 計算模式2 獲取離關機還有多少秒
        /// </summary>
        /// <param name="DateTime1">設定的關機時間</param>
        /// <param name="DateTime2">當前時間</param>
        /// <returns></returns>
        private double DateDiff(DateTime DateTime1, DateTime DateTime2)//計算模式2秒數
        {
            try
            {
                if (DateTime1 <= DateTime2)//關機時間必須是大於當前時間
                {
                    return 0.0;
                }
                //返回記錄關機的秒數
                return DateTime1.Subtract(DateTime2).Duration().TotalSeconds;
            }
            catch
            {
                return -1.0;
            }
        }
        /// <summary>
        /// 模式2確定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure2_Click(object sender, EventArgs e)//模式2確定
        {
            try
            {
                this.Cmd("shutdown -a");//取消之前的關機任務
                DateTime dTime = this.GetDTime();//獲取關機時間
                double sec = this.DateDiff(dTime, DateTime.Now);//獲取離關機還有多少秒
                //關機時間分為2秒~3天
                if ((sec > 2.0) && (sec < 259200.0))
                {
                    this.Cmd("shutdown -a");//取消之前的關機任務
                    //執行關機命令
                    this.Cmd("shutdown -s -t " + Convert.ToInt32(sec.ToString().Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0]).ToString());
                    //彈出訊息框提示使用者
                    MessageBox.Show("計算機將於" + this.GetDTime().ToString() + "關機");
                }
                else
                {
                    MessageBox.Show("選擇無效!!!");
                }

            }
            catch { }
        }
        /// <summary>
        /// 模式2取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)// 模式2取消
        {
            Cmd("shutdown -a");//取消關機任務
        }
        /// <summary>
        /// 當選項卡為模式2時,重置時間
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)//當選項卡為模式2時,重置時間
        {
            if (tabControl1.SelectedIndex == 1)
            {
                InitialModel2();
            }
        }



    }
    class Win32API //拖動介面
    {
        [DllImport("User32.dll")]
        public static extern bool PtInRect(ref Rectangle r, Point p);
    
    }

}

五、總結

      1、cmd關機相關命令

          取消任務命令:shutdown -a

          重啟命令:shutdown -r -t sec         (於sec秒後重啟)

          關機命令:shutdown -s -t sec        (於sec秒後關機)

                            at 23:00 shutdown -s        (在23:00執行shutdown -s,即在23:00關機。)

                            at 某個時間 執行某個動作/應用  (win7測試管理員許可權)

                       

                        取消at計劃(1是ID)

                        

      2、更改應用圖示

                               

3、窗體設定為無邊框樣式之後,就拖動不了了。可以通過監聽滑鼠動作,在窗體範圍內,窗體跟隨滑鼠的移動。對於貼邊其實就是設定窗體的位置。

4、呼叫第三方程式

                   

                    Process process = new Process()//建立程序
                    process.StartInfo.FileName = exePath;//exePath:呼叫程式的路徑
                    process.Start();//開始呼叫執行
                    process.WaitForExit();//等待退出
                    process.Close();//關閉程序