Example #1
0
def SetControlValue(hmixer, mixerControl, value):
    '''
    Sets the volumne from the pointer of the object passed through

    ' [Note: original source taken from MSDN
    http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q178456&]

    This function sets the value for a volume control. Returns True if
    successful
    '''

    valueDetails = MIXERCONTROLDETAILS_UNSIGNED()
    valueDetails.dwValue = value
    mixerControlDetails = MIXERCONTROLDETAILS()
    mixerControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS)
    mixerControlDetails.item = 0
    mixerControlDetails.dwControlID = mixerControl.dwControlID
    mixerControlDetails.cbDetails = sizeof(valueDetails)
    mixerControlDetails.paDetails = addressof(valueDetails)
    mixerControlDetails.cChannels = 1

    # Set the control value
    rc = mixerSetControlDetails(hmixer, byref(mixerControlDetails), 0)
    if rc != MMSYSERR_NOERROR:
        raise SoundMixerException()
Example #2
0
def GetDisplayModes():
    res = []
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    devMode = DEVMODE()
    devMode.dmSize = sizeof(DEVMODE)
    iDevNum = 0
    while True:
        if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
            break
        iDevNum += 1
        if displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER:
            continue
        EnumDisplaySettingsEx(
            displayDevice.DeviceName,
            ENUM_CURRENT_SETTINGS,
            pointer(devMode),
            0
        )
        displayMode = (
            displayDevice.DeviceName,
            devMode.dmPosition.x,
            devMode.dmPosition.y,
            devMode.dmPelsWidth,
            devMode.dmPelsHeight,
            devMode.dmDisplayFrequency,
            devMode.dmBitsPerPel,
            bool(
                displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
            ),
            bool(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE),
            devMode.dmDisplayFlags,
        )
        res.append(displayMode)
    return tuple(res)
Example #3
0
    def GetDeviceLines(self, deviceId=0):
        mixercaps = MIXERCAPS()
        mixerline = MIXERLINE()
        result = []

        hmixer = self.GetMixer(deviceId)
        if mixerGetDevCaps(hmixer, byref(mixercaps), sizeof(MIXERCAPS)):
            raise SoundMixerException()
        
        for i in range(mixercaps.cDestinations):
            mixerline.cbStruct = sizeof(MIXERLINE)
            mixerline.dwDestination = i
            if mixerGetLineInfo(hmixer, byref(mixerline), MIXER_GETLINEINFOF_DESTINATION):
                continue

            destination = mixerline.szName

            for control in self.GetControls(hmixer, mixerline):
                result.append((control[0], destination, None, control[1], control[2], control[3]))

            for n in range(mixerline.cConnections):
                mixerline.cbStruct = sizeof(MIXERLINE)
                mixerline.dwDestination = i
                mixerline.dwSource = n
                if mixerGetLineInfo(hmixer, byref(mixerline), MIXER_GETLINEINFOF_SOURCE):
                    continue
                source = mixerline.szName

                for control in self.GetControls(hmixer, mixerline):
                    result.append((control[0], destination, source, control[1], control[2], control[3]))
           
        return result
Example #4
0
def GetDeviceLines(deviceId=0):
    mixercaps = MIXERCAPS()
    mixerline = MIXERLINE()
    hmixer = HMIXER()

    # Obtain the hmixer struct
    rc = mixerOpen(byref(hmixer), deviceId, 0, 0, 0)
    if rc != MMSYSERR_NOERROR:
        raise SoundMixerException()

    if mixerGetDevCaps(hmixer, byref(mixercaps), sizeof(MIXERCAPS)):
        raise SoundMixerException()

    for destinationNum in range(mixercaps.cDestinations):
        mixerline.cbStruct = sizeof(MIXERLINE)
        mixerline.dwDestination = destinationNum
        if mixerGetLineInfo(
            hmixer, byref(mixerline), MIXER_GETLINEINFOF_DESTINATION
        ):
            continue
        print "Destination:", destinationNum, mixerline.szName
        for name in GetControls(hmixer, mixerline):
            print "        Control:", name
        for sourceNum in range(mixerline.cConnections):
            mixerline.cbStruct = sizeof(MIXERLINE)
            mixerline.dwDestination = destinationNum
            mixerline.dwSource = sourceNum
            if mixerGetLineInfo(
                hmixer, byref(mixerline), MIXER_GETLINEINFOF_SOURCE
            ):
                continue
            print "    Source:", sourceNum, mixerline.szName
            for name in GetControls(hmixer, mixerline):
                print "            Control:", name
Example #5
0
    def FillTree(self):
        root = self.AddRoot("Sound Card")
        mixercaps = MIXERCAPS()
        mixerline = MIXERLINE()
        self.mixerHandle = mixerHandle = HMIXER()

        # Obtain the hmixer struct
        rc = mixerOpen(byref(mixerHandle), self.deviceId, 0, 0, 0)
        if rc != MMSYSERR_NOERROR:
            raise SoundMixerException()

        if mixerGetDevCaps(mixerHandle, byref(mixercaps), sizeof(MIXERCAPS)):
            raise SoundMixerException()

        for i in range(mixercaps.cDestinations):
            mixerline.cbStruct = sizeof(MIXERLINE)
            mixerline.dwDestination = i
            if mixerGetLineInfo(mixerHandle, byref(mixerline), MIXER_GETLINEINFOF_DESTINATION):
                continue
            destItem = self.AppendItem(root, mixerline.szName + ": %i" % mixerline.cChannels)
            self.AddControls(destItem, mixerline)
            for n in range(mixerline.cConnections):
                mixerline.cbStruct = sizeof(MIXERLINE)
                mixerline.dwDestination = i
                mixerline.dwSource = n
                if mixerGetLineInfo(mixerHandle, byref(mixerline), MIXER_GETLINEINFOF_SOURCE):
                    continue
                sourceItem = self.AppendItem(
                    destItem,
                    mixerline.szName + ": %i" % mixerline.cChannels
                )
                self.AddControls(sourceItem, mixerline)
Example #6
0
def GetDisplayModes():
    res = []
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    devMode = DEVMODE()
    devMode.dmSize = sizeof(DEVMODE)
    iDevNum = 0
    while True:
        if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
            break
        iDevNum += 1
        if displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER:
            continue
        EnumDisplaySettingsEx(
            displayDevice.DeviceName,
            ENUM_CURRENT_SETTINGS,
            pointer(devMode),
            0
        )
        displayMode = (
            displayDevice.DeviceName,
            devMode.dmPosition.x,
            devMode.dmPosition.y,
            devMode.dmPelsWidth,
            devMode.dmPelsHeight,
            devMode.dmDisplayFrequency,
            devMode.dmBitsPerPel,
            bool(
                displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
            ),
            bool(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE),
            devMode.dmDisplayFlags,
        )
        res.append(displayMode)
    return tuple(res)
Example #7
0
    def ScanDevices(self):
        nDevices = UINT(0)
        if -1 == GetRawInputDeviceList(None, byref(nDevices),
                                       sizeof(RAWINPUTDEVICELIST)):
            raise WinError()
        rawInputDeviceList = (RAWINPUTDEVICELIST * nDevices.value)()
        if -1 == GetRawInputDeviceList(
                cast(rawInputDeviceList, PRAWINPUTDEVICELIST), byref(nDevices),
                sizeof(RAWINPUTDEVICELIST)):
            raise WinError()

        cbSize = UINT()
        for i in range(nDevices.value):
            GetRawInputDeviceInfo(rawInputDeviceList[i].hDevice,
                                  RIDI_DEVICENAME, None, byref(cbSize))
            deviceName = create_unicode_buffer(cbSize.value)
            GetRawInputDeviceInfo(rawInputDeviceList[i].hDevice,
                                  RIDI_DEVICENAME, byref(deviceName),
                                  byref(cbSize))
            ridDeviceInfo = RID_DEVICE_INFO()
            cbSize.value = ridDeviceInfo.cbSize = sizeof(RID_DEVICE_INFO)
            GetRawInputDeviceInfo(rawInputDeviceList[i].hDevice,
                                  RIDI_DEVICEINFO, byref(ridDeviceInfo),
                                  byref(cbSize))
            if ridDeviceInfo.dwType != RIM_TYPEKEYBOARD:
                continue
            print "hDevice:", rawInputDeviceList[i].hDevice
            print "Type:", RIM_TYPES[rawInputDeviceList[i].dwType]
            print "DeviceName:", deviceName.value
            if ridDeviceInfo.dwType == RIM_TYPEHID:
                hid = ridDeviceInfo.hid
                print "dwVendorId: %04X" % hid.dwVendorId
                print "dwProductId: %04X" % hid.dwProductId
                print "dwVersionNumber: %04X" % hid.dwVersionNumber
                print "usUsagePage:", hid.usUsagePage
                print "usUsage:", hid.usUsage
            if ridDeviceInfo.dwType == RIM_TYPEKEYBOARD:
                kbd = ridDeviceInfo.keyboard
                print "dwType:", kbd.dwType
                print "dwSubType:", kbd.dwSubType
                print "dwKeyboardMode:", kbd.dwKeyboardMode
                print "dwNumberOfFunctionKeys:", kbd.dwNumberOfFunctionKeys
                print "dwNumberOfIndicators:", kbd.dwNumberOfIndicators
                print "dwNumberOfKeysTotal:", kbd.dwNumberOfKeysTotal
            if ridDeviceInfo.dwType == RIM_TYPEMOUSE:
                mouse = ridDeviceInfo.mouse
                print "dwId:", mouse.dwId
                print "dwNumberOfButtons:", mouse.dwNumberOfButtons
                print "dwSampleRate:", mouse.dwSampleRate
                print "fHasHorizontalWheel:", mouse.fHasHorizontalWheel
            print
Example #8
0
    def SetControlValue(self, mixer, controlId, value):
        valueDetails = MIXERCONTROLDETAILS_UNSIGNED()
        valueDetails.dwValue = value

        mixerControlDetails = MIXERCONTROLDETAILS()
        mixerControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS)
        mixerControlDetails.item = 0
        mixerControlDetails.dwControlID = controlId
        mixerControlDetails.cbDetails = sizeof(valueDetails)
        mixerControlDetails.paDetails = addressof(valueDetails)
        mixerControlDetails.cChannels = 1

        rc = mixerSetControlDetails(mixer, byref(mixerControlDetails), 0)
        if rc != MMSYSERR_NOERROR:
            raise SoundMixerException()
Example #9
0
    def GetControl(self, mixer, controlId):
        mixerControl = MIXERCONTROL()
        mixerControl.cbStruct = sizeof(MIXERCONTROL)
        mixerLineControls = MIXERLINECONTROLS()
        mixerLineControls.cbStruct = sizeof(MIXERLINECONTROLS)

        mixerLineControls.dwControlID = controlId
        mixerLineControls.cControls = 1
        mixerLineControls.cbmxctrl = sizeof(mixerControl)
        mixerLineControls.pamxctrl = pointer(mixerControl)

        rc = mixerGetLineControls(mixer, byref(mixerLineControls), 1) #MIXER_GETLINECONTROLSF_ONEBYID
        if MMSYSERR_NOERROR != rc:
            raise SoundMixerException()
        return mixerControl
Example #10
0
 def OnRawInput(self, hwnd, mesg, wParam, lParam):
     pcbSize = UINT()
     GetRawInputData(
         lParam, RID_INPUT, None, byref(pcbSize), sizeof(RAWINPUTHEADER)
     )
     buf = create_string_buffer(pcbSize.value)
     GetRawInputData(
         lParam, RID_INPUT, buf, byref(pcbSize), sizeof(RAWINPUTHEADER)
     )
     pRawInput = cast(buf, POINTER(RAWINPUT))
     keyboard = pRawInput.contents.data.keyboard
     if keyboard.VKey == 0xFF:
         eg.eventThread.Call(eg.Print, "0xFF")
         return 0
      #print "Scan code:", keyboard.MakeCode
     info = ""
     mTime = time.clock()
     if keyboard.Message == WM_KEYDOWN:
         transition = "KEYDOWN"
     elif keyboard.Message == WM_KEYUP:
         transition = "KEYUP"
     else:
         transition = " %d" % keyboard.Message
     info = "%f " % mTime
     info += "RawI %s: %s(%d), " % (
         transition,
         VK_KEYS[keyboard.VKey],
         keyboard.VKey
     )
     if GetAsyncKeyState(162): #LCtrl
         info += "LCtrl "
     if GetAsyncKeyState(163): #RCtrl
         info += "RCtrl "
     info += "Scan: %d, " % keyboard.MakeCode
     info += "Extra: %d, " % keyboard.ExtraInformation
     info += "Device: %r, " % pRawInput.contents.header.hDevice
     #print "Flags:", keyboard.Flags
     rawKeyboardData = RawKeyboardData(
         keyboard.VKey,
         pRawInput.contents.header.hDevice,
         keyboard.Message in (WM_KEYDOWN, WM_SYSKEYDOWN),
         time.clock()
     )
     self.buf.append(rawKeyboardData)
     eg.eventThread.Call(eg.Print, info)
     if GET_RAWINPUT_CODE_WPARAM(wParam) == RIM_INPUT:
         return DefWindowProc(hwnd, mesg, wParam, lParam)
     return 0
Example #11
0
 def OnRawInput(self, hwnd, mesg, wParam, lParam):
     pcbSize = UINT()
     GetRawInputData(
         lParam, RID_INPUT, None, byref(pcbSize), sizeof(RAWINPUTHEADER)
     )
     buf = create_string_buffer(pcbSize.value)
     GetRawInputData(
         lParam, RID_INPUT, buf, byref(pcbSize), sizeof(RAWINPUTHEADER)
     )
     pRawInput = cast(buf, POINTER(RAWINPUT))
     keyboard = pRawInput.contents.data.keyboard
     if keyboard.VKey == 0xFF:
         eg.eventThread.Call(eg.Print, "0xFF")
         return 0
      #print "Scan code:", keyboard.MakeCode
     info = ""
     mTime = time.clock()
     if keyboard.Message == WM_KEYDOWN:
         transition = "KEYDOWN"
     elif keyboard.Message == WM_KEYUP:
         transition = "KEYUP"
     else:
         transition = " %d" % keyboard.Message
     info = "%f " % mTime
     info += "RawI %s: %s(%d), " % (
         transition,
         VK_KEYS[keyboard.VKey],
         keyboard.VKey
     )
     if GetAsyncKeyState(162): #LCtrl
         info += "LCtrl "
     if GetAsyncKeyState(163): #RCtrl
         info += "RCtrl "
     info += "Scan: %d, " % keyboard.MakeCode
     info += "Extra: %d, " % keyboard.ExtraInformation
     info += "Device: %r, " % pRawInput.contents.header.hDevice
     #print "Flags:", keyboard.Flags
     rawKeyboardData = RawKeyboardData(
         keyboard.VKey,
         pRawInput.contents.header.hDevice,
         keyboard.Message in (WM_KEYDOWN, WM_SYSKEYDOWN),
         time.clock()
     )
     self.buf.append(rawKeyboardData)
     eg.eventThread.Call(eg.Print, info)
     if GET_RAWINPUT_CODE_WPARAM(wParam) == RIM_INPUT:
         return DefWindowProc(hwnd, mesg, wParam, lParam)
     return 0
Example #12
0
def GetControlValue(hmixer, mixerControl):
    valueDetails = MIXERCONTROLDETAILS_UNSIGNED()

    mixerControlDetails = MIXERCONTROLDETAILS()
    mixerControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS)
    mixerControlDetails.item = 0
    mixerControlDetails.dwControlID = mixerControl.dwControlID
    mixerControlDetails.cbDetails = sizeof(valueDetails)
    mixerControlDetails.paDetails = addressof(valueDetails)
    mixerControlDetails.cChannels = 1

    # Get the control value
    rc = mixerGetControlDetails(hmixer, byref(mixerControlDetails), 0)
    if rc != MMSYSERR_NOERROR:
        raise SoundMixerException()
    return valueDetails.dwValue
Example #13
0
def EnsureVisible(window):
    """
    Ensures the given wx.TopLevelWindow is visible on the screen.
    Moves and resizes it if necessary.
    """
    from eg.WinApi.Dynamic import (
        sizeof, byref, GetMonitorInfo, MonitorFromWindow, GetWindowRect,
        MONITORINFO, RECT, MONITOR_DEFAULTTONEAREST,
        # MonitorFromRect, MONITOR_DEFAULTTONULL,
    )

    hwnd = window.GetHandle()
    windowRect = RECT()
    GetWindowRect(hwnd, byref(windowRect))

    #hMonitor = MonitorFromRect(byref(windowRect), MONITOR_DEFAULTTONULL)
    #if hMonitor:
    #    return

    parent = window.GetParent()
    if parent:
        hwnd = parent.GetHandle()
    hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)

    monInfo = MONITORINFO()
    monInfo.cbSize = sizeof(MONITORINFO)
    GetMonitorInfo(hMonitor, byref(monInfo))
    displayRect = monInfo.rcWork

    left = windowRect.left
    right = windowRect.right
    top = windowRect.top
    bottom = windowRect.bottom

    # shift the window horizontally into the display area
    if left < displayRect.left:
        right += (displayRect.left - left)
        left = displayRect.left
        if right > displayRect.right:
            right = displayRect.right
    elif right > displayRect.right:
        left += (displayRect.right - right)
        right = displayRect.right
        if left < displayRect.left:
            left = displayRect.left

    # shift the window vertically into the display area
    if top < displayRect.top:
        bottom += (displayRect.top - top)
        top = displayRect.top
        if bottom > displayRect.bottom:
            bottom = displayRect.bottom
    elif bottom > displayRect.bottom:
        top += (displayRect.bottom - bottom)
        bottom = displayRect.bottom
        if top < displayRect.top:
            top = displayRect.top

    # set the new position and size
    window.SetRect((left, top, right - left, bottom - top))
Example #14
0
def EnsureVisible(window):
    """
    Ensures the given wx.TopLevelWindow is visible on the screen.
    Moves and resizes it if necessary.
    """
    from eg.WinApi.Dynamic import (
        sizeof, byref, GetMonitorInfo, MonitorFromWindow, GetWindowRect,
        MONITORINFO, RECT, MONITOR_DEFAULTTONEAREST,
        # MonitorFromRect, MONITOR_DEFAULTTONULL,
    )

    hwnd = window.GetHandle()
    windowRect = RECT()
    GetWindowRect(hwnd, byref(windowRect))

    #hMonitor = MonitorFromRect(byref(windowRect), MONITOR_DEFAULTTONULL)
    #if hMonitor:
    #    return

    parent = window.GetParent()
    if parent:
        hwnd = parent.GetHandle()
    hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)

    monInfo = MONITORINFO()
    monInfo.cbSize = sizeof(MONITORINFO)
    GetMonitorInfo(hMonitor, byref(monInfo))
    displayRect = monInfo.rcWork

    left = windowRect.left
    right = windowRect.right
    top = windowRect.top
    bottom = windowRect.bottom

    # shift the window horizontally into the display area
    if left < displayRect.left:
        right += (displayRect.left - left)
        left = displayRect.left
        if right > displayRect.right:
            right = displayRect.right
    elif right > displayRect.right:
        left += (displayRect.right - right)
        right = displayRect.right
        if left < displayRect.left:
            left = displayRect.left

    # shift the window vertically into the display area
    if top < displayRect.top:
        bottom += (displayRect.top - top)
        top = displayRect.top
        if bottom > displayRect.bottom:
            bottom = displayRect.bottom
    elif bottom > displayRect.bottom:
        top += (displayRect.bottom - bottom)
        bottom = displayRect.bottom
        if top < displayRect.top:
            top = displayRect.top

    # set the new position and size
    window.SetRect((left, top, right - left, bottom - top))
Example #15
0
def GetDisplays():
    res = []
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    iDevNum = 0
    while True:
        if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
            break
        #DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1
        if not (displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER):
            disp = Display(iDevNum, displayDevice)
            res.append(disp)
            displayDevice = DISPLAY_DEVICE()
            displayDevice.cb = sizeof(DISPLAY_DEVICE)
        iDevNum += 1
    return res
Example #16
0
def GetDisplays():
    res = []
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    iDevNum = 0
    while True:
        if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
            break
        #DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1
        if not (displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER):
            disp = Display(iDevNum, displayDevice)
            res.append(disp)
            displayDevice = DISPLAY_DEVICE()
            displayDevice.cb = sizeof(DISPLAY_DEVICE)
        iDevNum += 1
    return res
def GetRam():
    memoryStatus = MEMORYSTATUSEX()
    memoryStatus.dwLength = sizeof(MEMORYSTATUSEX)
    GlobalMemoryStatusEx(byref(memoryStatus))
    return (
        round(memoryStatus.ullTotalPhys / 1024.0 / 1024 / 1024, 1),
        round(memoryStatus.ullAvailPhys / 1024.0 / 1024 / 1024, 1),
    )
Example #18
0
def GetRam():
    memoryStatus = MEMORYSTATUSEX()
    memoryStatus.dwLength = sizeof(MEMORYSTATUSEX)
    GlobalMemoryStatusEx(byref(memoryStatus))
    return (
        round(memoryStatus.ullTotalPhys / 1024.0 / 1024 / 1024, 1),
        round(memoryStatus.ullAvailPhys / 1024.0 / 1024 / 1024, 1),
    )
Example #19
0
def GetRam():
    memoryStatus = MEMORYSTATUSEX()
    memoryStatus.dwLength = sizeof(MEMORYSTATUSEX)
    GlobalMemoryStatusEx(byref(memoryStatus))
    return (
        int(round(memoryStatus.ullTotalPhys / 1048576.0)),
        int(round(memoryStatus.ullAvailPhys / 1048576.0)),
    )
Example #20
0
def GetMixerControl(componentType, ctrlType, deviceId=0):
    '''
    Obtains an appropriate pointer and info for the volume control
    This function attempts to obtain a mixer control. Raises
    SoundMixerException if not successful.
    '''
    hmixer = HMIXER()

    # Obtain the hmixer struct
    rc = mixerOpen(byref(hmixer), deviceId, 0, 0, 0)
    if rc != MMSYSERR_NOERROR:
        raise SoundMixerException()

    mixerLineControls = MIXERLINECONTROLS()
    mixerLineControls.cbStruct = sizeof(MIXERLINECONTROLS)
    mixerLine = MIXERLINE()
    mixerLine.cbStruct = sizeof(MIXERLINE)
    mixerControl = MIXERCONTROL()
    mixerControl.cbStruct = sizeof(MIXERCONTROL)

    mixerLine.dwComponentType = componentType

    # Obtain a line corresponding to the component type
    rc = mixerGetLineInfo(
        hmixer,
        byref(mixerLine),
        MIXER_GETLINEINFOF_COMPONENTTYPE
    )
    if rc != MMSYSERR_NOERROR:
        raise SoundMixerException()

    mixerLineControls.dwLineID = mixerLine.dwLineID
    mixerLineControls.dwControlType = ctrlType
    mixerLineControls.cControls = 1
    mixerLineControls.cbmxctrl = sizeof(mixerControl)
    mixerLineControls.pamxctrl = pointer(mixerControl)

    # Get the control
    rc = mixerGetLineControls(
        hmixer,
        byref(mixerLineControls),
        MIXER_GETLINECONTROLSF_ONEBYTYPE
    )
    if MMSYSERR_NOERROR != rc:
        raise SoundMixerException()
    return hmixer, mixerControl
Example #21
0
 def GetMixerDevices(self):
     mixcaps = MIXERCAPS()
     result = []
     for i in range(mixerGetNumDevs()):
         if mixerGetDevCaps(i, byref(mixcaps), sizeof(MIXERCAPS)):
             continue
         result.append((i, mixcaps.szPname))
     return result
Example #22
0
def GetRam():
    memoryStatus = MEMORYSTATUSEX()
    memoryStatus.dwLength = sizeof(MEMORYSTATUSEX)
    GlobalMemoryStatusEx(byref(memoryStatus))
    return (
        int(round(memoryStatus.ullTotalPhys / 1048576.0)),
        int(round(memoryStatus.ullAvailPhys / 1048576.0)),
    )
Example #23
0
 def __init__(self, iDevNum, displayDevice):
     self.iDevNum = iDevNum
     self.deviceName = displayDevice.DeviceName
     self.deviceString = displayDevice.DeviceString
     self.isPrimary = bool(
         displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE
     )
     self.devMode = DEVMODE()
     self.devMode.dmSize = sizeof(DEVMODE)
     self.dmp = pointer(self.devMode)
Example #24
0
 def __init__(self, iDevNum, displayDevice):
     self.iDevNum = iDevNum
     self.deviceName = displayDevice.DeviceName
     self.deviceString = displayDevice.DeviceString
     self.isPrimary = bool(
         displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE
     )
     self.devMode = DEVMODE()
     self.devMode.dmSize = sizeof(DEVMODE)
     self.dmp = pointer(self.devMode)
Example #25
0
    def OnCopyData(self, hwnd, mesg, wParam, lParam):
        copyData = cast(lParam, PCOPYDATASTRUCT)
        hEvent = cast(copyData.contents.lpData, POINTER(HEVENT))
        if not (
            copyData.contents.dwData == 0
            and copyData.contents.cbData == sizeof(HEVENT)
            and hEvent.contents.dwHookType == WH_KEYBOARD
        ):
            eg.eventThread.Call(eg.Print, "return")
            return
        mTime = time.clock()
        msg = MSG()
        while PeekMessage(byref(msg), 0, WM_INPUT, WM_INPUT, PM_REMOVE):
            self.OnRawInput(0, msg.message, msg.wParam, msg.lParam)
        vKey = hEvent.contents.wParam
        repeatCount = hEvent.contents.lParam & 0xFFFF
        keyState = (hEvent.contents.lParam >> 30) & 0x01
        extended = (hEvent.contents.lParam >> 24) & 0x01
        if (hEvent.contents.lParam >> 31) & 0x01:
            transition = "KEYUP"
            state = False
        else:
            transition = "KEYDOWN"
            state = True
        info = "%f Hook %s: %s(%d), keyState=%d, extended=%d" % (
            mTime,
            transition,
            VK_KEYS[vKey],
            hEvent.contents.wParam,
            keyState,
            extended,
        )
        if GetAsyncKeyState(162): #LCtrl
            info += "LCtrl "
        if GetAsyncKeyState(163): #RCtrl
            info += "RCtrl "
        i = 0
        while i < len(self.buf):
            rawKeyboardData = self.buf[i]
            if rawKeyboardData.tick < time.clock() - 0.2:
                eg.eventThread.Call(eg.Print, "*** removed to old message")
                del self.buf[i]
                continue
            if (
                rawKeyboardData.vKey == vKey
                and rawKeyboardData.state == state
            ):
                del self.buf[i]
#                if rawKeyboardData.device != 65603:
#                    eg.eventThread.Call(eg.Print, "blocked")
#                    return 1
                eg.eventThread.Call(eg.Print, info)
                return 0
            i += 1
        eg.eventThread.Call(eg.Print, "not found")
Example #26
0
    def OnCopyData(self, hwnd, mesg, wParam, lParam):
        copyData = cast(lParam, PCOPYDATASTRUCT)
        hEvent = cast(copyData.contents.lpData, POINTER(HEVENT))
        if not (
            copyData.contents.dwData == 0
            and copyData.contents.cbData == sizeof(HEVENT)
            and hEvent.contents.dwHookType == WH_KEYBOARD
        ):
            eg.eventThread.Call(eg.Print, "return")
            return
        mTime = time.clock()
        msg = MSG()
        while PeekMessage(byref(msg), 0, WM_INPUT, WM_INPUT, PM_REMOVE):
            self.OnRawInput(0, msg.message, msg.wParam, msg.lParam)
        vKey = hEvent.contents.wParam
        repeatCount = hEvent.contents.lParam & 0xFFFF
        keyState = (hEvent.contents.lParam >> 30) & 0x01
        extended = (hEvent.contents.lParam >> 24) & 0x01
        if (hEvent.contents.lParam >> 31) & 0x01:
            transition = "KEYUP"
            state = False
        else:
            transition = "KEYDOWN"
            state = True
        info = "%f Hook %s: %s(%d), keyState=%d, extended=%d" % (
            mTime,
            transition,
            VK_KEYS[vKey],
            hEvent.contents.wParam,
            keyState,
            extended,
        )
        if GetAsyncKeyState(162): #LCtrl
            info += "LCtrl "
        if GetAsyncKeyState(163): #RCtrl
            info += "RCtrl "
        i = 0
        while i < len(self.buf):
            rawKeyboardData = self.buf[i]
            if rawKeyboardData.tick < time.clock() - 0.2:
                eg.eventThread.Call(eg.Print, "*** removed to old message")
                del self.buf[i]
                continue
            if (
                rawKeyboardData.vKey == vKey
                and rawKeyboardData.state == state
            ):
                del self.buf[i]
#                if rawKeyboardData.device != 65603:
#                    eg.eventThread.Call(eg.Print, "blocked")
#                    return 1
                eg.eventThread.Call(eg.Print, info)
                return 0
            i += 1
        eg.eventThread.Call(eg.Print, "not found")
Example #27
0
 def __init__(self):
     self.dummyWindow = wx.Frame(None, -1, "Dummy Window")
     self.dummyHwnd = self.dummyWindow.GetHandle()
     self.msg = MSG()
     self.isSysKey = False
     self.sendInputStruct = INPUT()
     self.sendInputStruct.type = INPUT_KEYBOARD
     self.keyboardStateBuffer = PBYTE256()
     self.procHandle = None
     self.guiTreadInfo = GUITHREADINFO()
     self.guiTreadInfo.cbSize = sizeof(GUITHREADINFO)
Example #28
0
 def __init__(self):
     self.dummyWindow = wx.Frame(None, -1, "Dummy Window")
     self.dummyHwnd = self.dummyWindow.GetHandle()
     self.msg = MSG()
     self.isSysKey = False
     self.sendInputStruct = INPUT()
     self.sendInputStruct.type = INPUT_KEYBOARD
     self.keyboardStateBuffer = PBYTE256()
     self.procHandle = None
     self.guiTreadInfo = GUITHREADINFO()
     self.guiTreadInfo.cbSize = sizeof(GUITHREADINFO)
Example #29
0
def GetMixerDevices():
    """ Returns a list of all mixer device names available on the system."""
    mixcaps = MIXERCAPS()
    result = []
    # get the number of Mixer devices in this computer
    for i in range(mixerGetNumDevs()):
        # get info about the device
        if mixerGetDevCaps(i, byref(mixcaps), sizeof(MIXERCAPS)):
            continue
        # store the name of the device
        result.append(mixcaps.szPname)
    return result
Example #30
0
    def GetControls(self, hmixer, mixerline):
        numCtrls = mixerline.cControls
        if numCtrls == 0:
            return []

        mixerControlArray = (MIXERCONTROL * numCtrls)()
        mixerLineControls = MIXERLINECONTROLS()
        mixerLineControls.cbStruct = sizeof(MIXERLINECONTROLS)
        mixerLineControls.cControls = numCtrls
        mixerLineControls.dwLineID = mixerline.dwLineID
        mixerLineControls.pamxctrl = pointer(mixerControlArray[0])
        mixerLineControls.cbmxctrl = sizeof(MIXERCONTROL)
        mixerGetLineControls(hmixer, byref(mixerLineControls), MIXER_GETLINECONTROLSF_ALL)
        result = []

        for i in range(numCtrls):
            mixerControl = mixerControlArray[i]
            dwControlType = mixerControl.dwControlType
            controlClass = MIXER_CONTROL_CLASSES[dwControlType & MIXERCONTROL_CT_CLASS_MASK]
            controlClassTypeName = controlClass["types"][dwControlType]
            flagNames = []
            fdwControl =  mixerControl.fdwControl
            if fdwControl & MIXERCONTROL_CONTROLF_DISABLED:
                flagNames.append("Disabled")
            if fdwControl & MIXERCONTROL_CONTROLF_MULTIPLE:
                flagNames.append("Multiple(%i)" % mixerControl.cMultipleItems)
            if fdwControl & MIXERCONTROL_CONTROLF_UNIFORM:
                flagNames.append("Uniform")
            result.append(
                (
                    mixerControl.dwControlID,
                    mixerControl.szName, 
                    controlClass["name"], 
                    controlClassTypeName,
                    ", ".join(flagNames)
                )
            )

        return result
Example #31
0
def SetClipboardText(text):
    charBuffer = create_unicode_buffer(text)
    charBufferSize = sizeof(charBuffer)
    hGlobalMem = GlobalAlloc(GHND, charBufferSize)
    lpGlobalMem = GlobalLock(hGlobalMem)
    memcpy(lpGlobalMem, charBuffer, charBufferSize)
    GlobalUnlock(hGlobalMem)
    if not SafeOpenClipboard():
        return
    try:
        EmptyClipboard()
        SetClipboardData(CF_UNICODETEXT, hGlobalMem)
    finally:
        CloseClipboard()
Example #32
0
 def SetDisplayMode(self, size, frequency, bitdepth, flags=0):
     devMode = DEVMODE()
     devMode.dmSize = sizeof(DEVMODE)
     devMode.dmPelsWidth = size[0]
     devMode.dmPelsHeight = size[1]
     devMode.dmBitsPerPel = bitdepth
     devMode.dmDisplayFrequency = frequency
     devMode.dmFields = (
         DM_BITSPERPEL
         |DM_PELSWIDTH
         |DM_PELSHEIGHT
         |DM_DISPLAYFREQUENCY
     )
     ChangeDisplaySettingsEx(self.deviceName, pointer(devMode), 0, flags, 0)
Example #33
0
 def AddControls(self, parentItem, mixerline):
     numCtrls = mixerline.cControls
     if numCtrls == 0:
         return []
     mixerControlArray = (MIXERCONTROL * numCtrls)()
     mixerLineControls = MIXERLINECONTROLS()
     mixerLineControls.cbStruct = sizeof(MIXERLINECONTROLS)
     mixerLineControls.cControls = numCtrls
     mixerLineControls.dwLineID = mixerline.dwLineID
     mixerLineControls.pamxctrl = pointer(mixerControlArray[0])
     mixerLineControls.cbmxctrl = sizeof(MIXERCONTROL)
     mixerGetLineControls(
         self.mixerHandle,
         byref(mixerLineControls),
         MIXER_GETLINECONTROLSF_ALL
     )
     for i in range(numCtrls):
         mixerControl = mixerControlArray[i]
         ctrlItem = self.AppendItem(
             parentItem,
             mixerControl.szName
         )
         self.SetPyData(ctrlItem, mixerControl.dwControlID)
Example #34
0
 def SetDisplayMode(self, size, frequency, bitdepth, flags=0):
     devMode = DEVMODE()
     devMode.dmSize = sizeof(DEVMODE)
     devMode.dmPelsWidth = size[0]
     devMode.dmPelsHeight = size[1]
     devMode.dmBitsPerPel = bitdepth
     devMode.dmDisplayFrequency = frequency
     devMode.dmFields = (
         DM_BITSPERPEL
         |DM_PELSWIDTH
         |DM_PELSHEIGHT
         |DM_DISPLAYFREQUENCY
     )
     ChangeDisplaySettingsEx(self.deviceName, pointer(devMode), 0, flags, 0)
Example #35
0
def SetClipboardText(text):
    charBuffer = create_unicode_buffer(text)
    charBufferSize = sizeof(charBuffer)
    hGlobalMem = GlobalAlloc(GHND, charBufferSize)
    lpGlobalMem = GlobalLock(hGlobalMem)
    memcpy(lpGlobalMem, charBuffer, charBufferSize)
    GlobalUnlock(hGlobalMem)
    if not SafeOpenClipboard():
        return
    try:
        EmptyClipboard()
        SetClipboardData(CF_UNICODETEXT, hGlobalMem)
    finally:
        CloseClipboard()
Example #36
0
 def __start__(self):
     self.buf = collections.deque()
     self.ScanDevices()
     self.hookDll = CDLL(
         abspath(join(dirname(__file__), "RawInputHook.dll")))
     self.messageReceiver = eg.MessageReceiver("RawInputWindow")
     self.messageReceiver.AddHandler(WM_INPUT, self.OnRawInput)
     self.messageReceiver.AddHandler(WM_COPYDATA, self.OnCopyData)
     self.messageReceiver.Start()
     rid = (RAWINPUTDEVICE * 1)()
     rid[0].usUsagePage = 0x01
     rid[0].usUsage = 0x06
     rid[0].dwFlags = RIDEV_INPUTSINK
     rid[0].hwndTarget = self.messageReceiver.hwnd
     RegisterRawInputDevices(rid, 1, sizeof(rid[0]))
     self.hookDll.Start(self.messageReceiver.hwnd)
Example #37
0
 def __call__(
     self,
     pathname='',
     arguments='',
     winState=0,
     waitForCompletion=False,
     priority=2,
     workingDir=""
 ):
     returnValue = None
     pathname = eg.ParseString(pathname)
     if not workingDir:
         workingDir = dirname(abspath(pathname))
     arguments = eg.ParseString(arguments)
     commandLine = create_unicode_buffer('"%s" %s' % (pathname, arguments))
     startupInfo = STARTUPINFO()
     startupInfo.cb = sizeof(STARTUPINFO)
     startupInfo.dwFlags = STARTF_USESHOWWINDOW
     startupInfo.wShowWindow = WINSTATE_FLAGS[winState]
     priorityFlag = PRIORITY_FLAGS[priority]
     processInformation = PROCESS_INFORMATION()
     res = CreateProcess(
         None,              # lpApplicationName
         commandLine,       # lpCommandLine
         None,              # lpProcessAttributes
         None,              # lpThreadAttributes
         False,             # bInheritHandles
         priorityFlag|CREATE_NEW_CONSOLE, # dwCreationFlags
         None,              # lpEnvironment
         workingDir,        # lpCurrentDirectory
         startupInfo,       # lpStartupInfo
         processInformation # lpProcessInformation
     )
     if res == 0:
         raise self.Exception(FormatError())
     if waitForCompletion:
         WaitForSingleObject(processInformation.hProcess, INFINITE)
         exitCode = DWORD()
         if not GetExitCodeProcess(
             processInformation.hProcess,
             byref(exitCode)
         ):
             raise self.Exception(FormatError())
         returnValue = exitCode.value
     CloseHandle(processInformation.hProcess)
     CloseHandle(processInformation.hThread)
     return returnValue
Example #38
0
 def __start__(self):
     self.buf = collections.deque()
     self.ScanDevices()
     self.hookDll = CDLL(
         abspath(join(dirname(__file__), "RawInputHook.dll"))
     )
     self.messageReceiver = eg.MessageReceiver("RawInputWindow")
     self.messageReceiver.AddHandler(WM_INPUT, self.OnRawInput)
     self.messageReceiver.AddHandler(WM_COPYDATA, self.OnCopyData)
     self.messageReceiver.Start()
     rid = (RAWINPUTDEVICE * 1)()
     rid[0].usUsagePage = 0x01
     rid[0].usUsage = 0x06
     rid[0].dwFlags = RIDEV_INPUTSINK
     rid[0].hwndTarget = self.messageReceiver.hwnd
     RegisterRawInputDevices(rid, 1, sizeof(rid[0]))
     self.hookDll.Start(self.messageReceiver.hwnd)
Example #39
0
 def GetDisplayModes(self, allModes=False):
     devMode = DEVMODE()
     devMode.dmSize = sizeof(DEVMODE)
     lpDevMode = pointer(devMode)
     modes = {}
     if allModes:
         flag = EDS_RAWMODE
     else:
         flag = 0
     iModeNum = 0
     while 0 != EnumDisplaySettingsEx(self.deviceName, iModeNum, lpDevMode, flag):
         iModeNum += 1
         resolution = (devMode.dmPelsWidth, devMode.dmPelsHeight)
         deepthDict = modes.setdefault(resolution, {})
         frequencyList = deepthDict.setdefault(devMode.dmBitsPerPel, [])
         frequencyList.append(devMode.dmDisplayFrequency)
     return modes
Example #40
0
 def GetDisplayModes(self, allModes=False):
     devMode = DEVMODE()
     devMode.dmSize = sizeof(DEVMODE)
     lpDevMode = pointer(devMode)
     modes = {}
     if allModes:
         flag = EDS_RAWMODE
     else:
         flag = 0
     iModeNum = 0
     while 0 != EnumDisplaySettingsEx(
         self.deviceName, iModeNum, lpDevMode, flag
     ):
         iModeNum += 1
         resolution = (devMode.dmPelsWidth, devMode.dmPelsHeight)
         deepthDict = modes.setdefault(resolution, {})
         frequencyList = deepthDict.setdefault(devMode.dmBitsPerPel, [])
         frequencyList.append(devMode.dmDisplayFrequency)
     return modes
Example #41
0
 def GetAllPorts(cls):
     """
     Returns a list with all available serial ports.
     """
     serialPortList = cls._serialPortList
     if serialPortList is not None:
         return serialPortList
     serialPortList = []
     commconfig = COMMCONFIG()
     commconfig.dwSize = sizeof(COMMCONFIG)
     lpCC = pointer(commconfig)
     dwSize = DWORD(0)
     lpdwSize = byref(dwSize)
     for i in range(0, 255):
         name = 'COM%d' % (i+1)
         res = GetDefaultCommConfig(name, lpCC, lpdwSize)
         if res == 1 or (res == 0 and GetLastError() == 122):
             serialPortList.append(i)
     cls._serialPortList = serialPortList
     return serialPortList
Example #42
0
 def GetAllPorts(cls):
     """
     Returns a list with all available serial ports.
     """
     serialPortList = cls._serialPortList
     if serialPortList is not None:
         return serialPortList
     serialPortList = []
     commconfig = COMMCONFIG()
     commconfig.dwSize = sizeof(COMMCONFIG)
     lpCC = pointer(commconfig)
     dwSize = DWORD(0)
     lpdwSize = byref(dwSize)
     for i in range(0, 255):
         name = 'COM%d' % (i + 1)
         res = GetDefaultCommConfig(name, lpCC, lpdwSize)
         if res == 1 or (res == 0 and GetLastError() == 122):
             serialPortList.append(i)
     cls._serialPortList = serialPortList
     return serialPortList
Example #43
0
 def SendRawCodes1(self, keyData):
     """
     Uses the SendInput-API function to send the virtual keycode.
     Can only send to the frontmost window.
     """
     sendInputStruct = self.sendInputStruct
     sendInputStructPointer = pointer(sendInputStruct)
     sendInputStructSize = sizeof(sendInputStruct)
     keyboardStruct = sendInputStruct.ki
     for block in keyData:
         keyboardStruct.dwFlags = 0
         for virtualKey in block:
             keyboardStruct.wVk = virtualKey & 0xFF
             SendInput(1, sendInputStructPointer, sendInputStructSize)
             self.WaitForInputProcessed()
         keyboardStruct.dwFlags = KEYEVENTF_KEYUP
         for virtualKey in reversed(block):
             keyboardStruct.wVk = virtualKey & 0xFF
             SendInput(1, sendInputStructPointer, sendInputStructSize)
             self.WaitForInputProcessed()
Example #44
0
 def SendRawCodes1(self, keyData):
     """
     Uses the SendInput-API function to send the virtual keycode.
     Can only send to the frontmost window.
     """
     sendInputStruct = self.sendInputStruct
     sendInputStructPointer = pointer(sendInputStruct)
     sendInputStructSize = sizeof(sendInputStruct)
     keyboardStruct = sendInputStruct.ki
     for block in keyData:
         keyboardStruct.dwFlags = 0
         for virtualKey in block:
             keyboardStruct.wVk = virtualKey & 0xFF
             SendInput(1, sendInputStructPointer, sendInputStructSize)
             self.WaitForInputProcessed()
         keyboardStruct.dwFlags = KEYEVENTF_KEYUP
         for virtualKey in reversed(block):
             keyboardStruct.wVk = virtualKey & 0xFF
             SendInput(1, sendInputStructPointer, sendInputStructSize)
             self.WaitForInputProcessed()
Example #45
0
    def __init__(self, hFile=0):
        Thread.__init__(self, target=self.ReceiveThreadProc)
        self.hFile = int(hFile)
        self.osWriter = OVERLAPPED()
        self.osWriter.hEvent = CreateEvent(None, 0, 0, None)
        self.osReader = OVERLAPPED()
        self.osReader.hEvent = CreateEvent(None, 1, 0, None)
        self.dwRead = DWORD()
        self.comstat = COMSTAT()
        self.dcb = DCB()
        self.dcb.DCBlength = sizeof(DCB)
        self.oldCommTimeouts = COMMTIMEOUTS()

        self.readEventCallback = None
        self.readEventLock = Lock()
        self.readEventLock.acquire()
        self.readCondition = Condition()
        self.buffer = ""
        self.keepAlive = True
        self.stopEvent = CreateEvent(None, 1, 0, None)
        self.callbackThread = Thread(target=self.CallbackThreadProc, name="SerialReceiveThreadProc")
Example #46
0
    def __init__(self, hFile=0):
        Thread.__init__(self, target=self.ReceiveThreadProc)
        self.hFile = int(hFile)
        self.osWriter = OVERLAPPED()
        self.osWriter.hEvent = CreateEvent(None, 0, 0, None)
        self.osReader = OVERLAPPED()
        self.osReader.hEvent = CreateEvent(None, 1, 0, None)
        self.dwRead = DWORD()
        self.comstat = COMSTAT()
        self.dcb = DCB()
        self.dcb.DCBlength = sizeof(DCB)
        self.oldCommTimeouts = COMMTIMEOUTS()

        self.readEventCallback = None
        self.readEventLock = Lock()
        self.readEventLock.acquire()
        self.readCondition = Condition()
        self.buffer = ""
        self.keepAlive = True
        self.stopEvent = CreateEvent(None, 1, 0, None)
        self.callbackThread = Thread(target=self.CallbackThreadProc,
                                     name="SerialReceiveThreadProc")
Example #47
0
def SetDisplayModes(*args):
    for (
        deviceName,
        x,
        y,
        width,
        height,
        freq,
        bitdepth,
        isAttached,
        isPrimary,
        displayFlags
    ) in args:
        devMode = DEVMODE()
        devMode.dmSize = sizeof(DEVMODE)
        if isAttached:
            devMode.dmPosition.x = x
            devMode.dmPosition.y = y
            devMode.dmPelsWidth = width
            devMode.dmPelsHeight = height
            devMode.dmBitsPerPel = bitdepth
            devMode.dmDisplayFrequency = freq
            devMode.dmDisplayFlags = displayFlags
        devMode.dmFields = (
            DM_POSITION
            |DM_BITSPERPEL
            |DM_PELSWIDTH
            |DM_PELSHEIGHT
            |DM_DISPLAYFLAGS
            |DM_DISPLAYFREQUENCY
        )
        flags = (CDS_UPDATEREGISTRY | CDS_NORESET)
        if isPrimary:
            flags |= CDS_SET_PRIMARY
        ChangeDisplaySettingsEx(deviceName, pointer(devMode), 0, flags, 0)
    ChangeDisplaySettingsEx(None, None, 0, 0, 0)
Example #48
0
def SetDisplayModes(*args):
    for (
        deviceName,
        x,
        y,
        width,
        height,
        freq,
        bitdepth,
        isAttached,
        isPrimary,
        displayFlags
    ) in args:
        devMode = DEVMODE()
        devMode.dmSize = sizeof(DEVMODE)
        if isAttached:
            devMode.dmPosition.x = x
            devMode.dmPosition.y = y
            devMode.dmPelsWidth = width
            devMode.dmPelsHeight = height
            devMode.dmBitsPerPel = bitdepth
            devMode.dmDisplayFrequency = freq
            devMode.dmDisplayFlags = displayFlags
        devMode.dmFields = (
            DM_POSITION
            |DM_BITSPERPEL
            |DM_PELSWIDTH
            |DM_PELSHEIGHT
            |DM_DISPLAYFLAGS
            |DM_DISPLAYFREQUENCY
        )
        flags = (CDS_UPDATEREGISTRY | CDS_NORESET)
        if isPrimary:
            flags |= CDS_SET_PRIMARY
        ChangeDisplaySettingsEx(deviceName, pointer(devMode), 0, flags, 0)
    ChangeDisplaySettingsEx(None, None, 0, 0, 0)
Example #49
0
    def __call__(
        self,
        command='',
        waitForCompletion=True,
        triggerEvent=False,
        additionalSuffix="",
        disableParsingCommand=True,
        disableParsingAdditionalSuffix=True,
        payload=False,
        disableWOW64=False,
        runAsAdmin=False,
    ):
        if eg.config.refreshEnv:
            eg.Environment.Refresh()
        prefix = self.plugin.info.eventPrefix
        suffix = self.text.eventSuffix
        if additionalSuffix != "":
            suffix = "%s.%s" % (suffix, additionalSuffix)
        if not disableParsingCommand:
            command = eg.ParseString(command)
        if not disableParsingAdditionalSuffix:
            additionalSuffix = eg.ParseString(additionalSuffix)

        processInformation = self.processInformation = SHELLEXECUTEINFO()
        processInformation.cbSize = sizeof(processInformation)
        processInformation.hwnd = 0
        processInformation.lpFile = 'cmd.exe'
        if waitForCompletion or triggerEvent:
            si = STARTUPINFO()
            si.dwFlags |= STARTF_USESHOWWINDOW
            proc = popen("chcp", si)  # DOS console codepage
            data = proc.communicate()[0]
            if not proc.returncode:
                cp = "cp" + data.split()[-1].replace(".", "")
            proc.stdout.close()
            filename = join(eg.folderPath.TemporaryFiles,
                            "EventGhost-output-%s.txt" % ttime())
            processInformation.lpParameters = '/S/C "%s" > %s' % (command,
                                                                  filename)
            processInformation.fMask = SEE_MASK_NOCLOSEPROCESS
        else:
            processInformation.lpParameters = '/S/C "%s"' % command
        if runAsAdmin:
            processInformation.lpVerb = "runas"
        processInformation.nShow = 0
        processInformation.hInstApp = 0

        disableWOW64 = disableWOW64 and IsWin64()
        if disableWOW64:
            prevVal = Wow64DisableWow64FsRedirection()
        if not windll.shell32.ShellExecuteExW(byref(processInformation)):
            raise self.Exception(FormatError())
        if disableWOW64:
            Wow64RevertWow64FsRedirection(prevVal)
        if waitForCompletion:
            WaitForSingleObject(processInformation.hProcess, INFINITE)
            exitCode = DWORD()
            if not GetExitCodeProcess(processInformation.hProcess,
                                      byref(exitCode)):
                raise self.Exception(FormatError())
            try:
                data = code_open(filename, 'r', cp)
                lines = data.readlines()
                returnValue = "".join(lines)
                data.close()
                remove(filename)
            except:
                returnValue = ""

            if triggerEvent:
                if payload:
                    eg.TriggerEvent(suffix,
                                    prefix=prefix,
                                    payload=returnValue.rstrip())
                else:
                    eg.TriggerEvent(suffix, prefix=prefix)
            CloseHandle(processInformation.hProcess)
            return returnValue.rstrip()
        elif triggerEvent:
            te = self.TriggerEvent(processInformation, suffix, prefix,
                                   filename, cp, payload)
            te.start()
        else:
            CloseHandle(processInformation.hProcess)
Example #50
0
    def __call__(
        self,
        pathname='',
        arguments='',
        winState=0,
        waitForCompletion=False,
        priority=2,
        workingDir="",
        triggerEvent=False,
        disableWOW64=False,
    ):
        returnValue = None
        pathname = eg.ParseString(pathname)
        if not workingDir:
            workingDir = dirname(abspath(pathname))
        arguments = eg.ParseString(arguments)
        commandLine = create_unicode_buffer('"%s" %s' % (pathname, arguments))
        startupInfo = STARTUPINFO()
        startupInfo.cb = sizeof(STARTUPINFO)
        startupInfo.dwFlags = STARTF_USESHOWWINDOW
        startupInfo.wShowWindow = WINSTATE_FLAGS[winState]
        priorityFlag = PRIORITY_FLAGS[priority]
        processInformation = self.processInformation = PROCESS_INFORMATION()
        disableWOW64 = disableWOW64 and IsWin64()
        if disableWOW64:
            prevVal = Wow64DisableWow64FsRedirection()
        res = CreateProcess(
            None,  # lpApplicationName
            commandLine,  # lpCommandLine
            None,  # lpProcessAttributes
            None,  # lpThreadAttributes
            False,  # bInheritHandles
            priorityFlag | CREATE_NEW_CONSOLE,  # dwCreationFlags
            None,  # lpEnvironment
            workingDir,  # lpCurrentDirectory
            startupInfo,  # lpStartupInfo
            processInformation  # lpProcessInformation
        )
        if disableWOW64:
            Wow64RevertWow64FsRedirection(prevVal)
        suffix = "%s.%s" % (self.text.eventSuffix, splitext(
            split(pathname)[1])[0])
        prefix = self.plugin.name.replace(' ', '')
        if res == 0:
            raise self.Exception(FormatError())
        if winState != 3 and PluginIsEnabled("Task"):

            def callback(dummyHwnd, dummyMesg, wParam, lParam):
                pids = GetPids(hwnd=lParam)
                pid = pids[0] if pids else False
                if pid == processInformation.dwProcessId:
                    try:
                        eg.messageReceiver.RemoveHandler(
                            WM_SHELLHOOKMESSAGE, refCallback)
                    except:
                        pass
                    sleep(0.3)  # Wait for windows to appear
                    hwnds = GetHwnds(pid=processInformation.dwProcessId)
                    if hwnds:
                        #print "Focused via GetHwnds"
                        for hwnd in hwnds:
                            if IsWindowVisible(hwnd):
                                BringHwndToFront(hwnd)
                                break
                    elif IsWindowVisible(lParam):
                        #print "Focused via ShellHook"
                        BringHwndToFront(lParam)
                elif not ProcessExists(processInformation.dwProcessId):
                    try:
                        eg.messageReceiver.RemoveHandler(
                            WM_SHELLHOOKMESSAGE, refCallback)
                    except:
                        pass
                    try:
                        eg.plugins.Window.FindWindow(basename(pathname))
                        if len(eg.lastFoundWindows):
                            #print "Focused via FindWindow"
                            BringHwndToFront(eg.lastFoundWindows[0])
                    except:
                        pass

            refCallback = callback
            WM_SHELLHOOKMESSAGE = RegisterWindowMessage("SHELLHOOK")
            eg.messageReceiver.AddHandler(WM_SHELLHOOKMESSAGE, callback)
        if waitForCompletion:
            WaitForSingleObject(processInformation.hProcess, INFINITE)
            exitCode = DWORD()
            if not GetExitCodeProcess(processInformation.hProcess,
                                      byref(exitCode)):
                raise self.Exception(FormatError())
            returnValue = exitCode.value
            if triggerEvent:
                eg.TriggerEvent(suffix, prefix=prefix)
            CloseHandle(processInformation.hProcess)
            CloseHandle(processInformation.hThread)
            return returnValue
        elif triggerEvent:
            te = self.TriggerEvent(processInformation, suffix, prefix)
            te.start()
        else:
            CloseHandle(processInformation.hProcess)
            CloseHandle(processInformation.hThread)
Example #51
0
 def __init__(self, dbcc_devicetype=0, dbcc_classguid=None):
     self.dbcc_devicetype = dbcc_devicetype
     CLSIDFromString(dbcc_classguid, self.dbcc_classguid)
     self.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE)
Example #52
0
    FILE_NOTIFY_CHANGE_FILE_NAME,
    FILE_NOTIFY_CHANGE_DIR_NAME,
    FILE_NOTIFY_CHANGE_ATTRIBUTES,
    FILE_NOTIFY_CHANGE_SIZE,
    FILE_NOTIFY_CHANGE_LAST_WRITE,
    FILE_NOTIFY_CHANGE_SECURITY,
    FILE_LIST_DIRECTORY,
    FILE_ACTION_ADDED,
    FILE_ACTION_REMOVED,
    FILE_ACTION_MODIFIED,
    FILE_ACTION_RENAMED_OLD_NAME,
    FILE_ACTION_RENAMED_NEW_NAME,
)

BUFSIZE = 8192
WCHAR_SIZE = sizeof(WCHAR)

class Text:
    watchPath = "Watch path:"
    watchSubDirs = "Watch subdirectories also"



class DirectoryWatcher(eg.PluginClass):
    text = Text

    def __start__(self, path, includeSubdirs):
        self.stopEvent = CreateEvent(None, 1, 0, None)
        self.path = path
        self.startException = None
        self.includeSubdirs = includeSubdirs
Example #53
0
def GetDisplay(displayNum):
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    if EnumDisplayDevices(None, displayNum, pointer(displayDevice), 0) == 0:
        return None
    return Display(displayNum, displayDevice)
Example #54
0
    def __call__(
        self,
        pathname='',
        arguments='',
        winState=0,
        waitForCompletion=False,
        priority=2,
        workingDir="",
        triggerEvent=False,
        disableWOW64=False,
        additionalSuffix="",
        disableParsingPathname=False,
        disableParsingArguments=False,
        disableParsingAdditionalSuffix=False,
        runAsAdmin=False,
    ):
        if eg.config.refreshEnv:
            eg.Environment.Refresh()
        returnValue = None
        pathname = expandvars(pathname)
        arguments = expandvars(arguments)
        workingDir = expandvars(workingDir)
        if not disableParsingPathname:
            pathname = eg.ParseString(pathname)
        if not disableParsingArguments:
            arguments = eg.ParseString(arguments)
        if not disableParsingAdditionalSuffix:
            additionalSuffix = eg.ParseString(additionalSuffix)
        if not workingDir:
            workingDir = dirname(abspath(pathname))
        processInformation = self.processInformation = SHELLEXECUTEINFO()
        processInformation.cbSize = sizeof(processInformation)
        processInformation.hwnd = 0
        processInformation.lpFile = pathname
        processInformation.lpParameters = arguments
        processInformation.lpDirectory = workingDir
        processInformation.nShow = WINSTATE_FLAGS[winState]
        processInformation.hInstApp = 0
        processInformation.fMask = SEE_MASK_NOCLOSEPROCESS
        if runAsAdmin:
            processInformation.lpVerb = "runas"
        disableWOW64 = disableWOW64 and IsWin64()
        if disableWOW64:
            prevVal = Wow64DisableWow64FsRedirection()
        activeThread = GetWindowThreadProcessId(GetForegroundWindow(), None)
        currentThread = GetCurrentThreadId()
        attached = AttachThreadInput(currentThread, activeThread, True)

        if not windll.shell32.ShellExecuteExW(byref(processInformation)):
            raise self.Exception(FormatError())

        if attached:
            AttachThreadInput(currentThread, activeThread, False)
        if disableWOW64:
            Wow64RevertWow64FsRedirection(prevVal)
        if priority != 2:
            try:
                SetPriorityClass(processInformation.hProcess,
                                 PRIORITY_FLAGS[priority])
                priorityClass = GetPriorityClass(processInformation.hProcess)
                if priorityClass != PRIORITY_FLAGS[priority]:
                    raise
            except:
                pid = windll.kernel32.GetProcessId(processInformation.hProcess)
                pi = SHELLEXECUTEINFO()
                pi.cbSize = sizeof(pi)
                pi.lpFile = r"C:\Windows\System32\wbem\wmic.exe"
                pi.lpParameters = (
                    "process where processid=%d CALL setpriority %d" %
                    (pid, PRIORITY_FLAGS[priority]))
                pi.lpVerb = "runas"
                if not windll.shell32.ShellExecuteExW(byref(pi)):
                    eg.PrintError(self.text.priorityIssue)
        suffix = "%s.%s" % (self.text.eventSuffix, splitext(
            split(pathname)[1])[0])
        if additionalSuffix != "":
            suffix = suffix + "." + additionalSuffix
        prefix = self.plugin.name.replace(' ', '')
        if waitForCompletion:
            WaitForSingleObject(processInformation.hProcess, INFINITE)
            exitCode = DWORD()
            if not GetExitCodeProcess(processInformation.hProcess,
                                      byref(exitCode)):
                raise self.Exception(FormatError())
            returnValue = exitCode.value
            if triggerEvent:
                eg.TriggerEvent(suffix, prefix=prefix)
            CloseHandle(processInformation.hProcess)
            return returnValue
        elif triggerEvent:
            te = self.TriggerEvent(processInformation, suffix, prefix)
            te.start()
        else:
            CloseHandle(processInformation.hProcess)