科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道基础软件Visual C#中调用Windows服务初探

Visual C#中调用Windows服务初探

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

Windows服务是独立于登录用户而工作的Windows应用程序,它通常在计算机启动时开始执行

作者:佚名 来源:爱雪儿工作室 2007年11月13日

关键字:

  • 评论
  • 分享微博
  • 分享邮件
以下是careeye.cs的源程序:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
namespace CareEye
{
 public class CareEye : System.ServiceProcess.ServiceBase
 {
  private Thread MainThread;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public CareEye()
  {
   // 该调用是 Windows.Forms 组件设计器所必需的。
   InitializeComponent();

   // TODO: 在 InitComponent 调用后添加任何初始化
   MainThread=new Thread(new ThreadStart(ThreadFunc));
   MainThread.Priority=ThreadPriority.Lowest;
  }

  // 进程的主入口点
  static void Main()
  {
   //System.ServiceProcess.ServiceBase[] ServicesToRun;

   // 同一进程中可以运行多个用户服务。若要将
   //另一个服务添加到此进程,请更改下行
   // 以创建另一个服务对象。例如,
   //
   // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new CareEye(), new MySecondUserService()};
   //
   //ServicesToRun = new System.ServiceProcess.ServiceBase[] { new CareEye() };

   System.ServiceProcess.ServiceBase.Run(new CareEye());
  }

  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器
  /// 修改此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   //
   // CareEye
   //
   this.ServiceName = "CareEye";

  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  /// <summary>
  /// 设置具体的操作,以便服务可以执行它的工作。
  /// </summary>
  protected override void OnStart(string[] args)
  {
   // TODO: 在此处添加代码以启动服务。
   MainThread.Start();
  }

  /// <summary>
  /// 停止此服务。
  /// </summary>
  protected override void OnStop()
  {
   // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
   MainThread.Abort();
  }
  public static void ThreadFunc()
  {
   int LastHour=DateTime.Now.Hour;
   while (true)
   {
    System.Threading.Thread.Sleep(60000);
    if (DateTime.Now.Hour-1==LastHour)
    {
     MessageBox.Show("为了爱护您的眼睛,请您暂时休息5分钟并向远处眺望!","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button1,MessageBoxOptions.DefaultDesktopOnly);
LastHour=DateTime.Now.Hour;
    }
   }
  }
 }
}

查看本文来源

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章