C#将客户端创建为windowsservice

时间:2016-02-05 07:13:41

标签: c#

我正在做一个WindowsService程序,它每隔一秒自动进行一次屏幕捕获并将其设置为dir。当我运行它只工作一次。 我该怎么做?这是我的代码。

protected override void OnStart(string[] args)
{
    timer1_Tick();
}
private void timer1_Tick()
{
    string myDir = "c:\\Newfolder\\photo";
    System.IO.Directory.CreateDirectory(myDir);
    Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height);
    Graphics graphics = Graphics.FromImage(bitmap as Image);
    graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
    string fileName = string.Format(@"c:\Newfolder\photo\Screenshot" +"_" + DateTime.Now.ToString("(dd_MMMM_hh_mm_ss_tt)") + ".png");
    bitmap.Save(fileName, ImageFormat.Png);
}

2 个答案:

答案 0 :(得分:1)

在OnStart方法中删除对timer1_tick的调用,并添加以下内容:

timer1.enabled = true;
timer1.interval = 10000; //change this to whatever you need
timer1.Start();

如果您已将tick事件附加到计时器,则提供此项。

答案 1 :(得分:1)

static void Main()
    {if DEBUG
        Service1 Myservice = new Service1();
        Myservice.OnDebug();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);endif
    }