交互式Windows服务?

时间:2018-06-28 05:52:26

标签: python windows service ctypes

我用Python创建了Windows服务,并尝试通过 来自ctypes的GetForegroundWindow()。 要检查PC是否被锁定(当PC锁定时,GetForegroundWindow()==,在正常的Python Skript中可以正常工作)

显然,该服务必须是“交互服务”才能识别当前窗口。

所以问题是:是否可以将服务作为交互式服务启动?

Windows服务的结构是这样的(我删除了代码的某些部分,因此发布的时间并不长):

class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "Service"
    _svc_display_name_ = "Service"


    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        # Create an event which we will use to wait on.
        # The "service stop" request will set this event.
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        # Tell ReportServiceStatus we are starting the stop process.
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, waitHint=10000)

        # And set stop event.
        win32event.SetEvent(self.hWaitStop)

    def GetAcceptedControls(self):

        result = win32serviceutil.ServiceFramework.GetAcceptedControls(self)
        result |= win32service.SERVICE_ACCEPT_PRESHUTDOWN
        return result

    def SvcOtherEx(self, control, event_type, data):

        if control == win32service.SERVICE_CONTROL_PRESHUTDOWN:
            #_log('received a pre-shutdown notification')
            self.SvcStop()

    def SvcDoRun(self):
        user32 = ctypes.windll.User32
        #Do Something 

        while True:
            time.sleep(1)
            print(str(user32.GetForegroundWindow()))

        # Wait until the Service is stopped
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

1 个答案:

答案 0 :(得分:0)

  

是否可以将服务作为交互式服务启动?

我不建议这样做。

您应该创建一个在用户桌面环境中运行的进程。参见CreateProcessAsUser()。然后,该过程可以具有GUI并与您的服务进行通信。

我,在所有建议下,您仍然想创建一个交互式服务,请阅读MSDN on Interactive Services。请注意,在大多数情况下,这会使PC面临安全风险。

相关问题