0

好的,所以我正在创建一个 Windows 服务,它将根据用户是否登录来启动和停止我的渲染可执行文件。我已经确定我想从服务运行 exe,并且知道它将运行没有 gui 的安全桌面。这对我来说不是问题。

问题是我的服务在我告诉它启动时会立即启动。我认为这意味着我缺少某种循环或事件处理程序或某些东西,但我不知道是什么。这是我尝试编程的第一个服务。由于似乎没有办法有效地调试服务,我希望能从这里的聪明人那里得到一些意见。

任何输入将不胜感激!这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;

namespace SessionService
{
    public partial class renderServ : ServiceBase
    {
        private readonly ManagementClass _wmiComputerSystem = new ManagementClass("Win32_ComputerSystem");
        private Process process;
        Boolean isRunning;

        public renderServ()
        {
            InitializeComponent();

            process = new Process();
            process.StartInfo = new ProcessStartInfo(@"C:\Windows\notepad.exe");

            isRunning = false;
        }

        public void OnUserLogin()
        {
            /*if (isRunning == true)
            {
                process.Kill();
                process.WaitForExit();
            }*/
            isRunning = false;
        }

        public void OnUserLogoff()
        {
            if (isRunning == false)
            {
                process.Start();
                process.PriorityClass = ProcessPriorityClass.Idle;
            }
            isRunning = true;
        }

        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            base.OnSessionChange(changeDescription);

            switch (changeDescription.Reason)
            {
                case SessionChangeReason.SessionLogon:
                    {
                        OnUserLogin();
                    } break;
                case SessionChangeReason.SessionLogoff:
                    {
                        OnUserLogoff();
                    } break;
                case SessionChangeReason.SessionLock:
                    {
                        OnUserLogoff();
                    } break;
                case SessionChangeReason.SessionUnlock:
                    {
                        OnUserLogin();
                    } break;
            }
        }

        protected override void OnStart(string[] args)
        {
            CanHandleSessionChangeEvent = true;
            System.Windows.Forms.Application.Run();
        }

        protected override void OnStop()
        {
        }
    }
}
4

0 回答 0