示例#1
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
示例#2
0
    def MyWndProc(self, hwnd, mesg, wParam, lParam) :
        if mesg == WM_TIMER:
            keyHit = self.IR_GetSystemKeyCode(byref(self.repeatCode), byref(self.systemCode), byref(self.keyCode) );
            if  keyHit == 1:
                #print "RepeatCode = ", self.repeatCode, "  systemCode = ", self.systemCode, "  keyCode = ", self.keyCode, "  time = ", time()
                if self.timerKey :
                    self.timerKey.cancel()
                key    = self.keyCode.value
                repeat = ( self.repeatCode.value == 0 )
                if ( not repeat and self.checkRepeatFlag ) or not ( self.keyStillPressed and self.LastKeyCode == key ) :
                    self.LastKeyCode = key

                    if not self.systemCode.value in HauppaugeIRTable:
                        eventString = "%d" % key
                    elif key in HauppaugeIRTable[ self.systemCode.value ]:
                        eventString = HauppaugeIRTable[ self.systemCode.value ][key]
                    else:
                        eventString = "%d" % key

                    self.lastEvent = self.plugin.TriggerEnduringEvent(eventString)
                    self.keyStillPressed = True

                    releaseTime = self.waitTime
                else :
                    releaseTime = self.repeatReleaseTime

                self.timerKey = Timer(releaseTime, self.OnTimeOut)
                self.timerKey.start()
        return 1
示例#3
0
    def StatusCheckLoop(self):
        hComm = self.hFile
        waitingOnStatusHandle = False
        dwCommEvent = DWORD()
        dwOvRes = DWORD()
        commMask = (
            EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING
            | EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY
        )

        if not SetCommMask(self.hFile, commMask):
            raise SerialError("error setting communications mask")

        osStatus = OVERLAPPED(0)
        osStatus.hEvent = CreateEvent(None, 1, 0, None)
        if not osStatus.hEvent:
            raise SerialError("error creating event")

        while True:
            # Issue a status event check if one hasn't been issued already.
            if not waitingOnStatusHandle:
                if WaitCommEvent(hComm, byref(dwCommEvent), byref(osStatus)):
                    # WaitCommEvent returned immediately.
                    # Deal with status event as appropriate.
                    self.ReportStatusEvent(dwCommEvent.value)
                else:
                    if GetLastError() == ERROR_IO_PENDING:
                        waitingOnStatusHandle = True
                    else:
                        raise SerialError("error in WaitCommEvent")

            # Check on overlapped operation
            if waitingOnStatusHandle:
                # Wait a little while for an event to occur.
                res = WaitForSingleObject(osStatus.hEvent, 1000)
                if res == WAIT_OBJECT_0:
                    if GetOverlappedResult(
                        hComm, byref(osStatus), byref(dwOvRes), 0
                    ):
                        # Status event is stored in the event flag
                        # specified in the original WaitCommEvent call.
                        # Deal with the status event as appropriate.
                        self.ReportStatusEvent(dwCommEvent.value)
                    else:
                        # An error occurred in the overlapped operation;
                        # call GetLastError to find out what it was
                        # and abort if it is fatal.
                        raise SerialError()
                    # Set waitingOnStatusHandle flag to indicate that a new
                    # WaitCommEvent is to be issued.
                    waitingOnStatusHandle = True
                elif res == WAIT_TIMEOUT:
                    print "timeout"
                else:
                    # This indicates a problem with the OVERLAPPED structure's
                    # event handle.
                    CloseHandle(osStatus.hEvent)
                    raise SerialError("error in the WaitForSingleObject")

        CloseHandle(osStatus.hEvent)
示例#4
0
 def Write(self, data):
     """
     Writes a string to the port.
     """
     dwWritten = DWORD(0)
     returnValue = self._WriteFile(
         self.hFile,
         data,
         len(data),
         byref(dwWritten),
         byref(self.osWriter)
     )
     if returnValue != 0:
         return
     err = GetLastError()
     if err != 0 and err != ERROR_IO_PENDING:
         raise SerialError()
     if not GetOverlappedResult(
         self.hFile,
         byref(self.osWriter),
         byref(dwWritten),
         1
     ):
         raise SerialError()
     if dwWritten.value != len(data):
         raise self.SerialError("Write timeout")
示例#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)
示例#6
0
文件: Utils.py 项目: WoLpH/EventGhost
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))
示例#7
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
示例#8
0
    def MyWndProc(self, hwnd, mesg, wParam, lParam) :
        if mesg == WM_TIMER:
            keyHit = self.IR_GetSystemKeyCode(byref(self.repeatCode), byref(self.systemCode), byref(self.keyCode) );
            if  keyHit == 1:
                #print "RepeatCode = ", self.repeatCode, "  systemCode = ", self.systemCode, "  keyCode = ", self.keyCode, "  time = ", time()
                if self.timerKey :
                    self.timerKey.cancel()
                key    = self.keyCode.value
                repeat = ( self.repeatCode.value == 0 )
                if ( not repeat and self.checkRepeatFlag ) or not ( self.keyStillPressed and self.LastKeyCode == key ) :
                    self.LastKeyCode = key
                    
                    if not self.systemCode.value in HauppaugeIRTable:
                        eventString = "%d" % key
                    elif key in HauppaugeIRTable[ self.systemCode.value ]:
                        eventString = HauppaugeIRTable[ self.systemCode.value ][key]
                    else:
                        eventString = "%d" % key
                    
                    self.lastEvent = self.plugin.TriggerEnduringEvent(eventString)
                    self.keyStillPressed = True

                    releaseTime = self.waitTime
                else :                    
                    releaseTime = self.repeatReleaseTime

                self.timerKey = Timer(releaseTime, self.OnTimeOut)
                self.timerKey.start()
        return 1
示例#9
0
 def ThreadLoop(self, startupEvent):
     try:
         hDir = CreateFile(
             self.path, FILE_LIST_DIRECTORY,
             FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING,
             FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, 0)
         if hDir == INVALID_HANDLE_VALUE:
             self.startException = FormatError()
             startupEvent.set()
             return
         overlapped = OVERLAPPED()
         overlapped.hEvent = CreateEvent(None, 1, 0, None)
         buffer = (c_byte * BUFSIZE)()
         events = (HANDLE * 2)(overlapped.hEvent, self.stopEvent)
         flags = (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)
         includeSubdirs = self.includeSubdirs
         renamePath = None
         bytesReturned = DWORD()
         noneCallback = cast(None, LPOVERLAPPED_COMPLETION_ROUTINE)
         startupEvent.set()
         while 1:
             ReadDirectoryChangesW(hDir, buffer, BUFSIZE, includeSubdirs,
                                   flags, byref(bytesReturned),
                                   byref(overlapped), noneCallback)
             rc = MsgWaitForMultipleObjects(2, events, 0, INFINITE,
                                            QS_ALLINPUT)
             if rc == WAIT_OBJECT_0:
                 res = GetOverlappedResult(hDir, byref(overlapped),
                                           byref(bytesReturned), 1)
                 address = addressof(buffer)
                 while True:
                     fni = FILE_NOTIFY_INFORMATION.from_address(address)
                     length = fni.FileNameLength / WCHAR_SIZE
                     fileName = wstring_at(address + 12, length)
                     action = fni.Action
                     fullFilename = os.path.join(self.path, fileName)
                     if action == FILE_ACTION_ADDED:
                         self.TriggerEvent("Created", (fullFilename, ))
                     elif action == FILE_ACTION_REMOVED:
                         self.TriggerEvent("Deleted", (fullFilename, ))
                     elif action == FILE_ACTION_MODIFIED:
                         self.TriggerEvent("Updated", (fullFilename, ))
                     elif action == FILE_ACTION_RENAMED_OLD_NAME:
                         renamePath = fullFilename
                     elif action == FILE_ACTION_RENAMED_NEW_NAME:
                         self.TriggerEvent("Renamed",
                                           (renamePath, fullFilename))
                         renamePath = None
                     if fni.NextEntryOffset == 0:
                         break
                     address += fni.NextEntryOffset
             elif rc == WAIT_OBJECT_0 + 1:
                 break
         CloseHandle(hDir)
     except:
         self.thread = None
         raise
示例#10
0
 def __PumpWaitingMessages(self):
     msg = MSG()
     while PeekMessage(byref(msg), 0, 0, 0, PM_REMOVE):
         if msg.message == WM_QUIT:
             self.__alive = False
             return
         DispatchMessage(byref(msg))
示例#11
0
 def __PumpWaitingMessages(self):
     msg = MSG()
     while PeekMessage(byref(msg), 0, 0, 0, PM_REMOVE):
         if msg.message == WM_QUIT:
             self.__alive = False
             return
         DispatchMessage(byref(msg))
示例#12
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))
示例#13
0
    def StatusCheckLoop(self):
        hComm = self.hFile
        waitingOnStatusHandle = False
        dwCommEvent = DWORD()
        dwOvRes = DWORD()
        commMask = (
            EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING
            | EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY
        )

        if not SetCommMask(self.hFile, commMask):
            raise SerialError("error setting communications mask")

        osStatus = OVERLAPPED(0)
        osStatus.hEvent = CreateEvent(None, 1, 0, None)
        if not osStatus.hEvent:
            raise SerialError("error creating event")

        while True:
            # Issue a status event check if one hasn't been issued already.
            if not waitingOnStatusHandle:
                if WaitCommEvent(hComm, byref(dwCommEvent), byref(osStatus)):
                    # WaitCommEvent returned immediately.
                    # Deal with status event as appropriate.
                    self.ReportStatusEvent(dwCommEvent.value)
                else:
                    if GetLastError() == ERROR_IO_PENDING:
                        waitingOnStatusHandle = True
                    else:
                        raise SerialError("error in WaitCommEvent")

            # Check on overlapped operation
            if waitingOnStatusHandle:
                # Wait a little while for an event to occur.
                res = WaitForSingleObject(osStatus.hEvent, 1000)
                if res == WAIT_OBJECT_0:
                    if GetOverlappedResult(
                        hComm, byref(osStatus), byref(dwOvRes), 0
                    ):
                        # Status event is stored in the event flag
                        # specified in the original WaitCommEvent call.
                        # Deal with the status event as appropriate.
                        self.ReportStatusEvent(dwCommEvent.value)
                    else:
                        # An error occurred in the overlapped operation;
                        # call GetLastError to find out what it was
                        # and abort if it is fatal.
                        raise SerialError()
                    # Set waitingOnStatusHandle flag to indicate that a new
                    # WaitCommEvent is to be issued.
                    waitingOnStatusHandle = True
                elif res == WAIT_TIMEOUT:
                    print "timeout"
                else:
                    # This indicates a problem with the OVERLAPPED structure's
                    # event handle.
                    CloseHandle(osStatus.hEvent)
                    raise SerialError("error in the WaitForSingleObject")

        CloseHandle(osStatus.hEvent)
示例#14
0
def PumpWaitingMessages():
    msg = MSG()
    # PM_REMOVE = 0x0001
    while PeekMessage(byref(msg), 0, 0, 0, PM_REMOVE):
        if msg.message == WM_QUIT:
            return 1
        DispatchMessage(byref(msg))
示例#15
0
    def ReceiveThreadProc(self):
        hFile = self.hFile
        osReader = self.osReader
        lpBuf = create_string_buffer(1)
        dwRead = DWORD()
        pHandles = (HANDLE * 2)(osReader.hEvent, self.stopEvent)

        waitingOnRead = False
        while self.keepAlive:
            #print "ReceiveThreadProc"
            # if no read is outstanding, then issue another one
            if not waitingOnRead:
                #print "ResetEvent"
                ResetEvent(osReader.hEvent)
                returnValue = self._ReadFile(
                    hFile,
                    lpBuf,
                    1, # we want to get notified as soon as a byte is available
                    byref(dwRead),
                    byref(osReader)
                )
                if not returnValue:
                    err = GetLastError()
                    if err != 0 and err != ERROR_IO_PENDING:
                        raise SerialError()
                    waitingOnRead = True
                else:
                    # read completed immediately
                    if dwRead.value:
                        self.HandleReceive(lpBuf.raw)
                        continue

            ret = MsgWaitForMultipleObjects(
                2, pHandles, 0, 100000, QS_ALLINPUT
            )
            if ret == WAIT_OBJECT_0:
                returnValue = GetOverlappedResult(
                    hFile,
                    byref(osReader),
                    byref(dwRead),
                    0
                )
                #print "GetOverlappedResult", returnValue, dwRead.value
                waitingOnRead = False
                if returnValue and dwRead.value:
                    self.HandleReceive(lpBuf.raw)
            elif ret == WAIT_OBJECT_0 + 1:
                #print "WAIT_OBJECT_1"
                # stop event signaled
                self.readCondition.acquire()
                self.readCondition.notifyAll()
                self.readCondition.release()
                break
            elif ret == WAIT_TIMEOUT:
                #print "WAIT_TIMEOUT"
                pass
            else:
                raise SerialError("Unknown message in ReceiveThreadProc")
示例#16
0
    def ReceiveThreadProc(self):
        hFile = self.hFile
        osReader = self.osReader
        lpBuf = create_string_buffer(1)
        dwRead = DWORD()
        pHandles = (HANDLE * 2)(osReader.hEvent, self.stopEvent)

        waitingOnRead = False
        while self.keepAlive:
            #print "ReceiveThreadProc"
            # if no read is outstanding, then issue another one
            if not waitingOnRead:
                #print "ResetEvent"
                ResetEvent(osReader.hEvent)
                returnValue = self._ReadFile(
                    hFile,
                    lpBuf,
                    1, # we want to get notified as soon as a byte is available
                    byref(dwRead),
                    byref(osReader)
                )
                if not returnValue:
                    err = GetLastError()
                    if err != 0 and err != ERROR_IO_PENDING:
                        raise SerialError()
                    waitingOnRead = True
                else:
                    # read completed immediately
                    if dwRead.value:
                        self.HandleReceive(lpBuf.raw)
                        continue

            ret = MsgWaitForMultipleObjects(
                2, pHandles, 0, 100000, QS_ALLINPUT
            )
            if ret == WAIT_OBJECT_0:
                returnValue = GetOverlappedResult(
                    hFile,
                    byref(osReader),
                    byref(dwRead),
                    0
                )
                #print "GetOverlappedResult", returnValue, dwRead.value
                waitingOnRead = False
                if returnValue and dwRead.value:
                    self.HandleReceive(lpBuf.raw)
            elif ret == WAIT_OBJECT_0 + 1:
                #print "WAIT_OBJECT_1"
                # stop event signaled
                self.readCondition.acquire()
                self.readCondition.notifyAll()
                self.readCondition.release()
                break
            elif ret == WAIT_TIMEOUT:
                #print "WAIT_TIMEOUT"
                pass
            else:
                raise SerialError("Unknown message in ReceiveThreadProc")
示例#17
0
    def SendRawCodes2(self, keyData, hwnd, mode):
        """
        Uses PostMessage and SetKeyboardState to emulate the the virtual
        keycode. Can send to a specified window handle.
        """
        keyboardStateBuffer = self.keyboardStateBuffer
        for block in keyData:
            if mode == 1 or mode == 2:
                for virtualKey in block:
                    keyCode = virtualKey & 0xFF
                    highBits = virtualKey & 0xFF00
                    lparam = ((MapVirtualKey(keyCode, 0) | highBits) << 16) | 1

                    keyboardStateBuffer[keyCode] |= 128

                    if keyCode == VK_LSHIFT:
                        keyboardStateBuffer[VK_SHIFT] |= 128
                    #elif keyCode == VK_MENU:
                    #    self.isSysKey = True
                    elif keyCode == VK_CONTROL:
                        keyboardStateBuffer[VK_LCONTROL] |= 128

                    if self.isSysKey:
                        mesg = WM_SYSKEYDOWN
                        lparam |= 0x20000000
                    else:
                        mesg = WM_KEYDOWN

                    SetKeyboardState(byref(keyboardStateBuffer))
                    PostMessage(hwnd, mesg, keyCode, lparam)
                    self.WaitForInputProcessed()

            if mode == 0 or mode == 2:
                for virtualKey in reversed(block):
                    keyCode = virtualKey & 0xFF
                    highBits = virtualKey & 0xFF00
                    lparam = (
                        ((MapVirtualKey(keyCode, 0) | highBits) << 16) |
                        0xC0000001
                    )
                    keyboardStateBuffer[keyCode] &= ~128

                    if keyCode == VK_LSHIFT:
                        keyboardStateBuffer[VK_SHIFT] &= ~128
                    #elif keyCode == VK_MENU:
                    #    self.isSysKey = False
                    elif keyCode == VK_CONTROL:
                        keyboardStateBuffer[VK_LCONTROL] &= ~128

                    if self.isSysKey:
                        mesg = WM_SYSKEYUP
                        lparam |= 0x20000000
                    else:
                        mesg = WM_KEYUP

                    SetKeyboardState(byref(keyboardStateBuffer))
                    PostMessage(hwnd, mesg, keyCode, lparam)
                    self.WaitForInputProcessed()
示例#18
0
    def SendRawCodes2(self, keyData, hwnd, mode):
        """
        Uses PostMessage and SetKeyboardState to emulate the the virtual
        keycode. Can send to a specified window handle.
        """
        keyboardStateBuffer = self.keyboardStateBuffer
        for block in keyData:
            if mode == 1 or mode == 2:
                for virtualKey in block:
                    keyCode = virtualKey & 0xFF
                    highBits = virtualKey & 0xFF00
                    lparam = ((MapVirtualKey(keyCode, 0) | highBits) << 16) | 1

                    keyboardStateBuffer[keyCode] |= 128

                    if keyCode == VK_LSHIFT:
                        keyboardStateBuffer[VK_SHIFT] |= 128
                    #elif keyCode == VK_MENU:
                    #    self.isSysKey = True
                    elif keyCode == VK_CONTROL:
                        keyboardStateBuffer[VK_LCONTROL] |= 128

                    if self.isSysKey:
                        mesg = WM_SYSKEYDOWN
                        lparam |= 0x20000000
                    else:
                        mesg = WM_KEYDOWN

                    SetKeyboardState(byref(keyboardStateBuffer))
                    PostMessage(hwnd, mesg, keyCode, lparam)
                    self.WaitForInputProcessed()

            if mode == 0 or mode == 2:
                for virtualKey in reversed(block):
                    keyCode = virtualKey & 0xFF
                    highBits = virtualKey & 0xFF00
                    lparam = (
                        ((MapVirtualKey(keyCode, 0) | highBits) << 16) |
                        0xC0000001
                    )
                    keyboardStateBuffer[keyCode] &= ~128

                    if keyCode == VK_LSHIFT:
                        keyboardStateBuffer[VK_SHIFT] &= ~128
                    #elif keyCode == VK_MENU:
                    #    self.isSysKey = False
                    elif keyCode == VK_CONTROL:
                        keyboardStateBuffer[VK_LCONTROL] &= ~128

                    if self.isSysKey:
                        mesg = WM_SYSKEYUP
                        lparam |= 0x20000000
                    else:
                        mesg = WM_KEYUP

                    SetKeyboardState(byref(keyboardStateBuffer))
                    PostMessage(hwnd, mesg, keyCode, lparam)
                    self.WaitForInputProcessed()
示例#19
0
    def __call__(self,
                 hwnd,
                 keystrokeString,
                 useAlternateMethod=False,
                 mode=2):
        keyData = ParseText(keystrokeString)
        if keyData:
            needGetFocus = False
            sendToFront = False
            if hwnd is None:
                sendToFront = True
                hwnd = GetForegroundWindow()
                needGetFocus = True

            dwProcessId = DWORD()
            threadID = GetWindowThreadProcessId(hwnd, byref(dwProcessId))
            processID = dwProcessId.value
            ourThreadID = GetCurrentThreadId()

            # If not, attach our thread's 'input' to the foreground thread's
            if threadID != ourThreadID:
                AttachThreadInput(threadID, ourThreadID, True)

            if needGetFocus:
                hwnd = GetFocus()
            if not sendToFront:
                if GetGUIThreadInfo(0, byref(self.guiTreadInfo)):
                    sendToFront = (self.guiTreadInfo.hwndFocus == hwnd)
                else:
                    sendToFront = False
            if not hwnd:
                hwnd = None
            self.procHandle = OpenProcess(PROCESS_QUERY_INFORMATION, 0,
                                          processID)
            #self.WaitForInputProcessed()

            oldKeyboardState = PBYTE256()
            GetKeyboardState(byref(oldKeyboardState))

            keyData = ParseText(keystrokeString)
            if sendToFront and not useAlternateMethod:
                self.SendRawCodes1(keyData, mode)
            else:
                self.SendRawCodes2(keyData, hwnd, mode)

            SetKeyboardState(byref(oldKeyboardState))
            self.WaitForInputProcessed()
            if threadID != ourThreadID:
                AttachThreadInput(threadID, ourThreadID, False)
            if self.procHandle:
                CloseHandle(self.procHandle)
示例#20
0
    def __call__(self, hwnd, keystrokeString, useAlternateMethod=False, mode=2):
        keyData = ParseText(keystrokeString)
        if keyData:
            needGetFocus = False
            sendToFront = False
            if hwnd is None:
                sendToFront = True
                hwnd = GetForegroundWindow()
                needGetFocus = True

            dwProcessId = DWORD()
            threadID = GetWindowThreadProcessId(hwnd, byref(dwProcessId))
            processID = dwProcessId.value
            ourThreadID = GetCurrentThreadId()

            # If not, attach our thread's 'input' to the foreground thread's
            if threadID != ourThreadID:
                AttachThreadInput(threadID, ourThreadID, True)

            if needGetFocus:
                hwnd = GetFocus()
            if not sendToFront:
                if GetGUIThreadInfo(0, byref(self.guiTreadInfo)):
                    sendToFront = (self.guiTreadInfo.hwndFocus == hwnd)
                else:
                    sendToFront = False
            if not hwnd:
                hwnd = None
            self.procHandle = OpenProcess(
                PROCESS_QUERY_INFORMATION,
                0,
                processID
            )
            #self.WaitForInputProcessed()

            oldKeyboardState = PBYTE256()
            GetKeyboardState(byref(oldKeyboardState))

            keyData = ParseText(keystrokeString)
            if sendToFront and not useAlternateMethod:
                self.SendRawCodes1(keyData, mode)
            else:
                self.SendRawCodes2(keyData, hwnd, mode)

            SetKeyboardState(byref(oldKeyboardState))
            self.WaitForInputProcessed()
            if threadID != ourThreadID:
                AttachThreadInput(threadID, ourThreadID, False)
            if self.procHandle:
                CloseHandle(self.procHandle)
示例#21
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
示例#22
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
示例#23
0
    def __call__(self, drive=None, action=0):
        drive = drive or self.plugin.cdDrives[0]

        def SendCodeToDrive(code):
            device = getDeviceHandle(drive)
            try:
                hDevice = CreateFile(
                    device,
                    GENERIC_READ,
                    FILE_SHARE_READ,
                    None,
                    OPEN_EXISTING,
                    0,
                    0
                )
            except Exception, exc:
                self.PrintError(
                    "Couldn't find drive %s:" % drive[:1].upper()
                )
                return
            bytesReturned = DWORD()
            DeviceIoControl(
                hDevice, # handle to the device
                code,    # control code for the operation
                None,    # pointer to the input buffer
                0,       # size of the input buffer
                None,    # pointer to the output buffer
                0,       # size of the output buffer
                byref(bytesReturned),
                None     # pointer to an OVERLAPPED structure
            )
            CloseHandle(hDevice)
    def Setup(self, plugin, msgQueue):
        self.plugin = plugin
        self.msgQueue = msgQueue

        self.wndClass = WNDCLASS(
            lpfnWndProc = WNDPROC(self.WindowProc),
            hInstance = GetModuleHandle(None),
            lpszClassName = "HiddenPCTVMessageReceiver"
        )
        if not RegisterClass(byref(self.wndClass)):
            raise WinError()

        self.hWnd = CreateWindow(
            self.wndClass.lpszClassName,
            self.wndClass.lpszClassName,
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            None,
            None,
            self.wndClass.hInstance,
            None
        )
        if not self.hWnd:
            raise WinError()

        if not SetProp(self.hWnd, self.wndClass.lpszClassName, 658020):
            raise WinError()
示例#25
0
        def run(self):
            WaitForSingleObject(self.processInformation.hProcess, INFINITE)
            exitCode = DWORD()
            if not GetExitCodeProcess(
                self.processInformation.hProcess,
                byref(exitCode)
            ):
                raise self.Exception(FormatError())
            CloseHandle(self.processInformation.hProcess)
            if hasattr(self.processInformation, "hThread"):
                CloseHandle(self.processInformation.hThread)
            if self.pld:
                try:
                    data = code_open(self.filename, 'r', self.cp)
                    lines = data.readlines()
                    returnValue = "".join(lines)
                    data.close()
                    remove(self.filename)
                except:
                    returnValue = ""

                eg.TriggerEvent(
                    self.suffix,
                    prefix = self.prefix,
                    payload = returnValue.rstrip()
                )
            else:
                eg.TriggerEvent(self.suffix, prefix = self.prefix)
示例#26
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()
示例#27
0
 def __call__(self, x, y, displayNumber = 0):
     monitorDimensions = GetMonitorDimensions()
     try:
         displayRect = monitorDimensions[displayNumber]
     except IndexError:
         displayRect = monitorDimensions[0]
     rect = RECT()
     mons = EnumDisplayMonitors(None, None)
     mons = [item[2] for item in mons]
     for hwnd in GetTopLevelOfTargetWindows():
         GetWindowRect(hwnd, byref(rect))
         X = rect.left
         Y = rect.top
         for mon in range(len(mons)):
             if mons[mon][0] <= X and X <= mons[mon][2] and mons[mon][1] <= Y and Y <= mons[mon][3]:
                 break
         if mon == len(mons):
             mon = 0
         if x is None:
             x = rect.left - mons[mon][0]
         if y is None:
             y = rect.top - mons[mon][1]
         x += displayRect[0]
         y += displayRect[1]
         MoveWindow(
             hwnd, x, y, rect.right - rect.left, rect.bottom - rect.top, 1
         )
 def __call__(self, x, y, displayNumber=0):
     monitorDimensions = GetMonitorDimensions()
     try:
         displayRect = monitorDimensions[displayNumber]
     except IndexError:
         displayRect = monitorDimensions[0]
     rect = RECT()
     mons = EnumDisplayMonitors(None, None)
     mons = [item[2] for item in mons]
     for hwnd in GetTopLevelOfTargetWindows():
         GetWindowRect(hwnd, byref(rect))
         X = rect.left
         Y = rect.top
         for mon in range(len(mons)):
             if mons[mon][0] <= X and X <= mons[mon][2] and mons[mon][
                     1] <= Y and Y <= mons[mon][3]:
                 break
         if mon == len(mons):
             mon = 0
         if x is None:
             x = rect.left - mons[mon][0]
         if y is None:
             y = rect.top - mons[mon][1]
         x += displayRect[0]
         y += displayRect[1]
         MoveWindow(hwnd, x, y, rect.right - rect.left,
                    rect.bottom - rect.top, 1)
示例#29
0
    def Setup(self, plugin, waitTime):
        """
        This will be called inside the thread at the beginning.
        """
        self.plugin = plugin
        self.waitTime = waitTime
        self.timer = Timer(0, self.OnTimeOut)
        self.lastEvent = None

        wc = WNDCLASS()
        wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = "HiddenMceMessageReceiver"
        wc.lpfnWndProc = WNDPROC(self.MyWndProc)
        if not RegisterClass(byref(wc)):
            raise WinError()
        self.hwnd = CreateWindowEx(0, wc.lpszClassName,
                                   "MCE Remote Message Receiver",
                                   WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
                                   CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                                   0, 0, wc.hInstance, None)
        if not self.hwnd:
            raise WinError()
        self.wc = wc
        self.hinst = wc.hInstance

        self.dll = WinDLL(os.path.join(PLUGIN_DIR, "MceIr.dll"))
        if not self.dll.MceIrRegisterEvents(self.hwnd):
            raise self.plugin.Exceptions.DeviceNotFound
        self.dll.MceIrSetRepeatTimes(1, 1)
示例#30
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),
    )
示例#31
0
 def Write(self, data):
     """
     Writes a string to the port.
     """
     dwWritten = DWORD(0)
     returnValue = self._WriteFile(self.hFile, data, len(data),
                                   byref(dwWritten), byref(self.osWriter))
     if returnValue != 0:
         return
     err = GetLastError()
     if err != 0 and err != ERROR_IO_PENDING:
         raise SerialError()
     if not GetOverlappedResult(self.hFile, byref(self.osWriter),
                                byref(dwWritten), 1):
         raise SerialError()
     if dwWritten.value != len(data):
         raise self.SerialError("Write timeout")
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),
    )
示例#33
0
 def _ReadAllAvailable(self):
     """
     Get all bytes currently in the drivers receive buffer.
     Only used internally.
     """
     sleep(0.001)
     errors = DWORD()
     self._ClearCommError(self.hFile, byref(errors), byref(self.comstat))
     numBytes = self.comstat.cbInQue
     if numBytes == 0:
         return ""
     # ResetEvent(self.osReader.hEvent)
     lpBuffer = create_string_buffer(numBytes)
     numberOfBytesRead = DWORD()
     if not self._ReadFile(self.hFile, lpBuffer, numBytes, byref(numberOfBytesRead), byref(self.osReader)):
         WaitForSingleObject(self.osReader.hEvent, INFINITE)
     return lpBuffer.raw[: numberOfBytesRead.value]
示例#34
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
示例#35
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)),
    )
示例#36
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
示例#37
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)),
    )
示例#38
0
 def _ReadAllAvailable(self):
     """
     Get all bytes currently in the drivers receive buffer.
     Only used internally.
     """
     sleep(0.001)
     errors = DWORD()
     self._ClearCommError(self.hFile, byref(errors), byref(self.comstat))
     numBytes = self.comstat.cbInQue
     if numBytes == 0:
         return ''
     #ResetEvent(self.osReader.hEvent)
     lpBuffer = create_string_buffer(numBytes)
     numberOfBytesRead = DWORD()
     if not self._ReadFile(self.hFile, lpBuffer, numBytes,
                           byref(numberOfBytesRead), byref(self.osReader)):
         WaitForSingleObject(self.osReader.hEvent, INFINITE)
     return lpBuffer.raw[:numberOfBytesRead.value]
示例#39
0
 def __call__(self, width=None, height=None):
     rect = RECT()
     for hwnd in GetTopLevelOfTargetWindows():
         GetWindowRect(hwnd, byref(rect))
         if width is None:
             width = rect.right - rect.left - 1
         if height is None:
             height = rect.bottom - rect.top - 1
         MoveWindow(hwnd, rect.left, rect.top, width + 1, height + 1, 1)
示例#40
0
 def run(self):
     WaitForSingleObject(self.processInformation.hProcess, INFINITE)
     exitCode = DWORD()
     if not GetExitCodeProcess(self.processInformation.hProcess,
                               byref(exitCode)):
         raise self.Exception(FormatError())
     CloseHandle(self.processInformation.hProcess)
     CloseHandle(self.processInformation.hThread)
     eg.TriggerEvent(self.suffix, prefix=self.prefix)
示例#41
0
 def run(self):
     WaitForSingleObject(self.processInformation.hProcess, INFINITE)
     exitCode = DWORD()
     if not GetExitCodeProcess(self.processInformation.hProcess, byref(exitCode)):
         raise self.Exception(FormatError())
     CloseHandle(self.processInformation.hProcess)
     if hasattr(self.processInformation, "hThread"):
         CloseHandle(self.processInformation.hThread)
     eg.TriggerEvent(self.suffix, prefix=self.prefix)
 def __call__(self, width=None, height=None):
     rect = RECT()
     for hwnd in GetTopLevelOfTargetWindows():
         GetWindowRect(hwnd, byref(rect))
         if width is None:
             width = rect.right - rect.left - 1
         if height is None:
             height = rect.bottom - rect.top - 1
         MoveWindow(hwnd, rect.left, rect.top, width + 1, height + 1, 1)
示例#43
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")
示例#44
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")
示例#45
0
    def SetMode(self, mode):
        """
        Sets the serial port mode setting from a string.

        See :meth:`Open` for a complete description of the mode string.
        """
        dcb = self.dcb
        dcb.ByteSize = int(mode[0])
        dcb.Parity = PARITY_S2V_DICT[mode[1].upper()]
        dcb.StopBits = STOPBITS_S2V_DICT[mode[2:]]
        SetCommState(self.hFile, byref(dcb))
示例#46
0
    def SetMode(self, mode):
        """
        Sets the serial port mode setting from a string.

        See :meth:`Open` for a complete description of the mode string.
        """
        dcb = self.dcb
        dcb.ByteSize = int(mode[0])
        dcb.Parity = PARITY_S2V_DICT[mode[1].upper()]
        dcb.StopBits = STOPBITS_S2V_DICT[mode[2:]]
        SetCommState(self.hFile, byref(dcb))
示例#47
0
 def __init__(self, hwnd):
     if not hwnd:
         raise ValueError("Invalid hwnd")
     self.hwnd = hwnd
     dwProcessId = DWORD()
     GetWindowThreadProcessId(hwnd, byref(dwProcessId))
     self.pid = dwProcessId.value
     self.name = splitext(GetProcessName(self.pid))[0]
     # The following may change during a window's lifetime
     self.cached_title = ourName if self.pid == GetProcessId(
     ) else GetWindowText(hwnd)
     self.cached_class = GetClassName(hwnd)
示例#48
0
def GetMachineKey():
    # Get the volume serial number of the system drive
    volumeSerialBuffer = DWORD()
    GetVolumeInformation("C:\\", None, 0, byref(volumeSerialBuffer), None, None, None, 0)
    value = volumeSerialBuffer.value
    volumeSerial = chr((value >> 24) & 0xFF) + chr((value >> 16) & 0xFF) + chr((value >> 8) & 0xFF) + chr(value & 0xFF)
    # The last 6 bytes of the UUID returned from UuidCreateSequential contain
    # the hardware MAC address.
    uuid = ctypes.create_string_buffer(16)
    ctypes.windll.rpcrt4.UuidCreateSequential(uuid)
    mac = uuid.raw[-6:]
    return volumeSerial + mac
示例#49
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
 def WriteFhz(self, telegramType, *args):
     maxTime = time.clock() + 1.0
     dwStatus = DWORD()
     while True:
         d2xx.FT_GetModemStatus(self.ftHandle, byref(dwStatus))
         if dwStatus.value & 0xFF == 48:
             break
         if time.clock() > maxTime:
             self.PrintError("FHZ timeout error!")
             return
         time.sleep(0.01)
     self.WriteFhzNoWait(telegramType, *args)
示例#51
0
 def WriteFhz(self, telegramType, *args):
     maxTime = time.clock() + 1.0
     dwStatus = DWORD()
     while True:
         d2xx.FT_GetModemStatus(self.ftHandle, byref(dwStatus))
         if dwStatus.value & 0xFF == 48:
             break
         if time.clock() > maxTime:
             self.PrintError("FHZ timeout error!")
             return
         time.sleep(0.01)
         #print "write sleep"
     self.WriteFhzNoWait(telegramType, *args)
def GetMachineKey():
    # Get the volume serial number of the system drive
    volumeSerialBuffer = DWORD()
    GetVolumeInformation("C:\\", None, 0, byref(volumeSerialBuffer), None,
                         None, None, 0)
    value = volumeSerialBuffer.value
    volumeSerial = (chr((value >> 24) & 0xFF) + chr((value >> 16) & 0xFF) +
                    chr((value >> 8) & 0xFF) + chr(value & 0xFF))
    # The last 6 bytes of the UUID returned from UuidCreateSequential contain
    # the hardware MAC address.
    uuid = ctypes.create_string_buffer(16)
    ctypes.windll.rpcrt4.UuidCreateSequential(uuid)
    mac = uuid.raw[-6:]
    return volumeSerial + mac
示例#53
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
def EnumProcesses():
    pids = {}
    hwnds = {}
    dwProcessId = DWORD()
    for hwnd in GetTopLevelWindowList(False):
        GetWindowThreadProcessId(hwnd, byref(dwProcessId))
        pid = dwProcessId.value
        if pid not in pids:
            processInfo = ProcessInfo(pid)
            pids[pid] = processInfo
        else:
            processInfo = pids[pid]
        processInfo.hwnds[hwnd] = WindowInfo(hwnd)
        hwnds[hwnd] = processInfo
    return pids, hwnds
示例#55
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()
示例#56
0
def EnumProcesses():
    names = {}
    hwnds = {}
    dwProcessId = DWORD()
    for hwnd in GetTopLevelWindowList(False):
        GetWindowThreadProcessId(hwnd, byref(dwProcessId))
        pid = dwProcessId.value
        name = splitext(GetProcessName(pid))[0]
        if name not in names:
            processInfo = ProcessInfo(name)
            names[name] = processInfo
        else:
            processInfo = names[name]
        processInfo.hwnds.add(hwnd)
        hwnds[hwnd] = processInfo
    return names, hwnds
示例#57
0
 def __init__(self, windowName):
     self.windowName = windowName
     self.messageProcs = {
         WM_SIZE: [self.WmSizeHandler],
     }
     eg.ThreadWorker.__init__(self)
     wndclass = WNDCLASS(
         lpfnWndProc=WNDPROC(self.WindowProc),
         hInstance=GetModuleHandle(None),
         lpszMenuName=None,
         lpszClassName=self.windowName + "MessageReceiver",
     )
     self.classAtom = RegisterClass(byref(wndclass))
     if not self.classAtom:
         raise WinError()
     self.wndclass = wndclass
     self.hwnd = None
     self.nextWmUserMsg = WM_USER + 1000
     self.wmUserHandlers = {}
     self.freeWmUserMsgs = []
示例#58
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
示例#59
0
    def Setup(  self,
                plugin,
                waitTime,
                pollTime,
                useDefaultPollTime,
                initTime = 15.0,
                checkRepeatFlag = False,
                repeatReleaseTime = 200 ):
        """
        This will be called inside the thread at the beginning.
        """
        self.lock = Lock()
        self.abort = False

        self.plugin = plugin
        self.waitTime = float(waitTime)/1000.0
        self.repeatReleaseTime = float(repeatReleaseTime)/1000.0
        self.pollTime = pollTime
        self.useDefaultPollTime = useDefaultPollTime
        self.defaultPollTime = -1

        self.LastKeyCode = -1

        self.checkRepeatFlag = checkRepeatFlag

        self.repeatCode = c_int(0)
        self.systemCode = c_int(0)
        self.keyCode    = c_int(0)

        self.lastEvent = eg.EventGhostEvent()
        self.keyStillPressed = False
        self.initTerminated = False

        self.timerInit = None
        self.timerKey = None

        self.hwnd = None
        self.dll  = None

        # load irremote.dll

        try:
            regHandle = _winreg.OpenKey(
                           _winreg.HKEY_LOCAL_MACHINE,
                           'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Hauppauge WinTV Infrared Remote',
                           0,
                           _winreg.KEY_READ
                        )

            InstallString = _winreg.QueryValueEx(regHandle, 'UninstallString')[0]

            _winreg.CloseKey( regHandle )

            irremoteDir = InstallString.partition(' ')[0].rsplit('\\',1)[0]

            dllPath = os.path.join(irremoteDir, "irremote.DLL")


            self.dll = windll.LoadLibrary(dllPath)
            self.dll = WinDLL(dllPath)

        except:
            plugin.PrintError("Couldn't find irremote.dll! Reinstalling the Hauppauge "
                   "WinTV Infrared Remote package can solve the problem."
                  )
            raise self.plugin.Exceptions.DeviceNotFound

        self.IR_Open             = WINFUNCTYPE( c_int, HWND, c_int, c_byte, c_int )
        self.IR_Close            = WINFUNCTYPE( c_int, HWND, c_int )
        self.IR_GetSystemKeyCode = WINFUNCTYPE( c_int, POINTER( c_int), POINTER( c_int), POINTER( c_int) )
        self.TIMERPROC           = WINFUNCTYPE( None, HWND, c_uint, c_uint, DWORD )

        self.IR_Open             = self.dll.IR_Open
        self.IR_Close            = self.dll.IR_Close
        self.IR_GetSystemKeyCode = self.dll.IR_GetSystemKeyCode

        wc = WNDCLASS()
        wc.hInstance = GetDesktopWindow()
        wc.lpszClassName = "HaupPluginEventSinkWndClass"
        wc.lpfnWndProc = WNDPROC(self.MyWndProc)
        if not RegisterClass(byref(wc)):
            raise WinError()
        self.hwnd = CreateWindow(
            wc.lpszClassName,
            "HaupaugePlugin Event Window",
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            0,
            0,
            wc.hInstance,
            None
        )
        if not self.hwnd:
            raise WinError()
        self.wc = wc
        self.hinst = wc.hInstance

        self.timerInit = Timer( initTime, self.PostInit)        # Init delayed init timer ( in case of standby problems)
        self.timerInit.start()