欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现定时关机小应用

程序员文章站 2023-02-14 18:58:38
c# 定时关机小应用(winform),供大家参考,具体内容如下 一、简述 记--使用winform实现的定时关机小应用。通过执行cmd命令实现的。(visual st...

c# 定时关机小应用(winform),供大家参考,具体内容如下

一、简述

记--使用winform实现的定时关机小应用。通过执行cmd命令实现的。(visual studio 2010旗舰版)

例子打包:链接

二、效果

C#实现定时关机小应用

C#实现定时关机小应用

三、工程结构及布局视图

C#实现定时关机小应用

C#实现定时关机小应用

四、源文件

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测试管理员权限)

C#实现定时关机小应用

取消at计划(1是id)

C#实现定时关机小应用

2、更改应用图标

C#实现定时关机小应用

C#实现定时关机小应用

3、窗体设置为无边框样式之后,就拖动不了了。可以通过监听鼠标动作,在窗体范围内,窗体跟随鼠标的移动。对于贴边其实就是设置窗体的位置。

4、调用第三方程序

process process = new process()//创建进程
process.startinfo.filename = exepath;//exepath:调用程序的路径
process.start();//开始调用执行
process.waitforexit();//等待退出
process.close();//关闭进程

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。