Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Detecting USB Device Insertion on Windows 10

I can't get the following code for Detecting USB Device Insertion to work on my Windows 10 (64 bit) computer with Python 3.7.

import win32serviceutil
import win32service
import win32event
import servicemanager

import win32gui
import win32gui_struct
struct = win32gui_struct.struct
pywintypes = win32gui_struct.pywintypes
import win32con


import ctypes

# Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be
# used for monkey-patching said module with correct handling
# of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE
def _UnpackDEV_BROADCAST (lparam):
  if lparam == 0: return None
  hdr_format = "iii"
  hdr_size = struct.calcsize (hdr_format)
  hdr_buf = win32gui.PyGetMemory (lparam, hdr_size)
  size, devtype, reserved = struct.unpack ("iii", hdr_buf)
  # Due to x64 alignment issues, we need to use the full format string over
  # the entire buffer.  ie, on x64:
  # calcsize('iiiP') != calcsize('iii')+calcsize('P')
  buf = win32gui.PyGetMemory (lparam, size)

  extra = {}
  if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
    fmt = hdr_format + "16s"
    _, _, _, guid_bytes = struct.unpack (fmt, buf[:struct.calcsize(fmt)])
    extra['classguid'] = pywintypes.IID (guid_bytes, True)
    extra['name'] = ctypes.wstring_at (lparam + struct.calcsize(fmt))
    raise NotImplementedError("unknown device type %d" % (devtype,))
  return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
win32gui_struct.UnpackDEV_BROADCAST = _UnpackDEV_BROADCAST

class DeviceEventService (win32serviceutil.ServiceFramework):

  _svc_name_ = "DevEventHandler"
  _svc_display_name_ = "Device Event Handler"
  _svc_description_ = "Handle device notification events"

  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__ (self, args)
    self.hWaitStop = win32event.CreateEvent (None, 0, 0, None)
    # Specify that we're interested in device interface
    # events for USB devices
    filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE (
    self.hDevNotify = win32gui.RegisterDeviceNotification (
      self.ssh, # copy of the service status handle

  # Add to the list of controls already handled by the underlying
  # ServiceFramework class. We're only interested in device events
  def GetAcceptedControls(self):
    rc = win32serviceutil.ServiceFramework.GetAcceptedControls (self)
    rc |= win32service.SERVICE_CONTROL_DEVICEEVENT
    return rc

  # Handle non-standard service events (including our device broadcasts)
  # by logging to the Application event log
  def SvcOtherEx(self, control, event_type, data):
    if control == win32service.SERVICE_CONTROL_DEVICEEVENT:
      info = win32gui_struct.UnpackDEV_BROADCAST(data)
      # This is the key bit here where you'll presumably
      # do something other than log the event. Perhaps pulse
      # a named event or write to a secure pipe etc. etc.
      if event_type == DBT_DEVICEARRIVAL:
        servicemanager.LogMsg (
          ("Device %s arrived" %, '')
      elif event_type == DBT_DEVICEREMOVECOMPLETE:
        servicemanager.LogMsg (
          ("Device %s removed" %, '')

  # Standard stuff for stopping and running service; nothing
  # specific to device notifications
  def SvcStop(self):
    self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent (self.hWaitStop)

  def SvcDoRun(self):
    win32event.WaitForSingleObject (self.hWaitStop, win32event.INFINITE)
    servicemanager.LogMsg (
      (self._svc_name_, '')

if __name__=='__main__':
  win32serviceutil.HandleCommandLine (DeviceEventService)

  1. I start the script with the following command:
    python start

  2. Then the following error messages appear in the command prompt:
    Starting service DevEventHandler Error starting service: Access denied
  3. I then ran the script with administrator privileges:
    runas /user:administrator "python start"

  4. Another error messages appear in the command prompt:
    Starting service DevEventHandler Error starting service: The specified service does not exist as an installed service.

How can the 'The specified service does not exist as an installed service' error be fixed?

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Get list of Video Device in python on Windows machine Michal 1 46 Apr-03-2020, 06:57 PM
Last Post: Mateusz
  Reading UDP from external device without device software ikdemartijn 2 228 Dec-03-2019, 04:29 PM
Last Post: Larz60+
  Detecting windows shutdown event riccardoob 4 366 Nov-12-2019, 04:51 PM
Last Post: Aurthor_King_of_the_Brittons
  Detecting String Elements in a List within Given Message Redicebergz 6 723 Mar-19-2019, 03:12 PM
Last Post: buran
  Detecting if image matches another kainev 2 568 Dec-02-2018, 02:00 PM
Last Post: kainev
  Detecting file extensions ellipsis 1 584 Nov-15-2018, 07:44 AM
Last Post: buran
  detecting mouse not working TheNumericDolfin 6 961 Aug-23-2018, 01:34 AM
Last Post: Windspar
  Detecting Windows System Sounds? crash2720 1 972 Jan-23-2018, 07:08 PM
Last Post: Larz60+
  Tree insertion and variable referencing hshivaraj 3 1,064 Dec-10-2017, 04:29 PM
Last Post: Windspar
  Change Windows Sound Output Device with Python delfar 1 2,537 Sep-15-2017, 12:11 AM
Last Post: Larz60+

Forum Jump:

Users browsing this thread: 1 Guest(s)