Python ctypes.windll() Examples

The following are 30 code examples of ctypes.windll(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def EnumWindows():
    _EnumWindows = windll.user32.EnumWindows
    _EnumWindows.argtypes = [WNDENUMPROC, LPARAM]
    _EnumWindows.restype = bool

    EnumFunc = __EnumWndProc()
    lpEnumFunc = WNDENUMPROC(EnumFunc)
    if not _EnumWindows(lpEnumFunc, NULL):
        errcode = GetLastError()
        if errcode not in (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
            raise ctypes.WinError(errcode)
    return EnumFunc.hwnd


# BOOL CALLBACK EnumChildProc(
#     HWND hwnd,
#     LPARAM lParam
# ); 
Example #2
Source File: test_circuitpython.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_workspace_dir_nt_missing():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'CIRCUITPY'
    does not exist for a device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    editor = mock.MagicMock()
    view = mock.MagicMock()
    am = CircuitPythonMode(editor, view)
    with mock.patch("os.name", "nt"):
        with mock.patch("os.path.exists", return_value=True):
            return_value = ctypes.create_unicode_buffer(1024)
            with mock.patch(
                "ctypes.create_unicode_buffer", return_value=return_value
            ), mock.patch(
                "mu.modes.circuitpython." "MicroPythonMode.workspace_dir"
            ) as mpm:
                mpm.return_value = "foo"
                ctypes.windll = mock_windll
                assert am.workspace_dir() == "foo" 
Example #3
Source File: test_circuitpython.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_workspace_dir_nt_exists():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'CIRCUITPY'
    exists indicating a connected device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    editor = mock.MagicMock()
    view = mock.MagicMock()
    am = CircuitPythonMode(editor, view)
    with mock.patch("os.name", "nt"):
        with mock.patch("os.path.exists", return_value=True):
            return_value = ctypes.create_unicode_buffer("CIRCUITPY")
            with mock.patch(
                "ctypes.create_unicode_buffer", return_value=return_value
            ):
                ctypes.windll = mock_windll
                assert am.workspace_dir() == "A:\\" 
Example #4
Source File: inputs.py    From inputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_input(self, ncode, wparam, lparam):
        """Process the key input."""
        value = WIN_KEYBOARD_CODES[wparam]
        scan_code = lparam.contents.scan_code
        vk_code = lparam.contents.vk_code
        self.update_timeval()

        events = []
        # Add key event
        scan_key, key_event = self.emulate_press(
            vk_code, scan_code, value, self.timeval)
        events.append(scan_key)
        events.append(key_event)

        # End with a sync marker
        events.append(self.sync_marker(self.timeval))

        # We are done
        self.write_to_pipe(events)

        return ctypes.windll.user32.CallNextHookEx(
            self.hooked, ncode, wparam, lparam) 
Example #5
Source File: inputs.py    From inputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _find_xinput(self):
        """Find most recent xinput library."""
        for dll in XINPUT_DLL_NAMES:
            try:
                self.xinput = getattr(ctypes.windll, dll)
            except OSError:
                pass
            else:
                # We found an xinput driver
                self.xinput_dll = dll
                break
        else:
            # We didn't find an xinput library
            warn(
                "No xinput driver dll found, gamepads not supported.",
                RuntimeWarning) 
Example #6
Source File: inputs.py    From inputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delay_and_stop(duration, dll, device_number):
    """Stop vibration aka force feedback aka rumble on
    Windows after duration miliseconds."""
    xinput = getattr(ctypes.windll, dll)
    time.sleep(duration/1000)
    xinput_set_state = xinput.XInputSetState
    xinput_set_state.argtypes = [
        ctypes.c_uint, ctypes.POINTER(XinputVibration)]
    xinput_set_state.restype = ctypes.c_uint
    vibration = XinputVibration(0, 0)
    xinput_set_state(device_number, ctypes.byref(vibration))


# I made this GamePad class before Mouse and Keyboard above, and have
# learned a lot about Windows in the process.  This can probably be
# simplified massively and made to match Mouse and Keyboard more. 
Example #7
Source File: inputs.py    From inputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_input(self, ncode, wparam, lparam):
        """Process the key input."""
        x_pos = lparam.contents.x_pos
        y_pos = lparam.contents.y_pos
        data = lparam.contents.mousedata

        # This is how we can distinguish mouse 1 from mouse 2
        # extrainfo = lparam.contents.extrainfo
        # The way windows seems to do it is there is primary mouse
        # and all other mouses report as mouse 2

        # Also useful later will be to support the flags field
        # flags = lparam.contents.flags
        # This shows if the event was from a real device or whether it
        # was injected somehow via software

        self.emulate_mouse(wparam, x_pos, y_pos, data)

        # Give back control to Windows to wait for and process the
        # next event
        return ctypes.windll.user32.CallNextHookEx(
            self.hooked, ncode, wparam, lparam) 
Example #8
Source File: pyperclip.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def _copyWindows(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(None)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #9
Source File: pyperclip.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def _copyWindows(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(None)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #10
Source File: clipboard.py    From passpie with MIT License 6 votes vote down vote up
def _copy_windows(text, clear=0):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll  # cdll expects 4 more bytes in user32.OpenClipboard(0)
    if not isinstance(text, unicode):
        text = text.decode('mbcs')

    d.user32.OpenClipboard(0 if is_python2() else None)

    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #11
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def EnumChildWindows(hWndParent=NULL):
    _EnumChildWindows = windll.user32.EnumChildWindows
    _EnumChildWindows.argtypes = [HWND, WNDENUMPROC, LPARAM]
    _EnumChildWindows.restype = bool

    EnumFunc = __EnumChildProc()
    lpEnumFunc = WNDENUMPROC(EnumFunc)
    SetLastError(ERROR_SUCCESS)
    _EnumChildWindows(hWndParent, lpEnumFunc, NULL)
    errcode = GetLastError()
    if errcode != ERROR_SUCCESS and errcode not in \
            (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
        raise ctypes.WinError(errcode)
    return EnumFunc.hwnd


# int WINAPI GetWindowText(
#   __in   HWND hWnd,
#   __out  LPTSTR lpString,
#   __in   int nMaxCount
# ); 
Example #12
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetWindowTextA(hWnd):
    _GetWindowTextA = windll.user32.GetWindowTextA
    _GetWindowTextA.argtypes = [HWND, LPSTR, ctypes.c_int]
    _GetWindowTextA.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(CHAR)
    while 1:
        lpString = ctypes.create_string_buffer(nMaxCount)
        nCount = _GetWindowTextA(hWnd, lpString, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpString.value) 
Example #13
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetClassNameA(hWnd):
    _GetClassNameA = windll.user32.GetClassNameA
    _GetClassNameA.argtypes = [HWND, LPSTR, ctypes.c_int]
    _GetClassNameA.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(CHAR)
    while 1:
        lpClassName = ctypes.create_string_buffer(nMaxCount)
        nCount = _GetClassNameA(hWnd, lpClassName, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpClassName.value) 
Example #14
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetClassNameW(hWnd):
    _GetClassNameW = windll.user32.GetClassNameW
    _GetClassNameW.argtypes = [HWND, LPWSTR, ctypes.c_int]
    _GetClassNameW.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(WCHAR)
    while 1:
        lpClassName = ctypes.create_unicode_buffer(nMaxCount)
        nCount = _GetClassNameW(hWnd, lpClassName, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpClassName.value) 
Example #15
Source File: __init__.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def FormatError(code):
        code = int(long(code))
        try:
            if GuessStringType.t_default == GuessStringType.t_ansi:
                FormatMessage = windll.kernel32.FormatMessageA
                FormatMessage.argtypes = [DWORD, LPVOID, DWORD, DWORD, LPSTR, DWORD]
                FormatMessage.restype  = DWORD
                lpBuffer = ctypes.create_string_buffer(1024)
            else:
                FormatMessage = windll.kernel32.FormatMessageW
                FormatMessage.argtypes = [DWORD, LPVOID, DWORD, DWORD, LPWSTR, DWORD]
                FormatMessage.restype  = DWORD
                lpBuffer = ctypes.create_unicode_buffer(1024)
            ##FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
            ##FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
            success = FormatMessage(0x1200, None, code, 0, lpBuffer, 1024)
            if success:
                return lpBuffer.value
        except Exception:
            pass
        if GuessStringType.t_default == GuessStringType.t_ansi:
            return "Error code 0x%.8X" % code
        return u"Error code 0x%.8X" % code 
Example #16
Source File: test_uflash.py    From uflash with MIT License 6 votes vote down vote up
def test_find_microbit_nt_exists():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'MICROBIT'
    exists indicating a connected micro:bit device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    #
    # Have every drive claim to be removable
    #
    mock_windll.kernel32.GetDriveTypeW = mock.MagicMock()
    mock_windll.kernel32.GetDriveTypeW.return_value = 2
    with mock.patch('os.name', 'nt'):
        with mock.patch('os.path.exists', return_value=True):
            return_value = ctypes.create_unicode_buffer('MICROBIT')
            with mock.patch('ctypes.create_unicode_buffer',
                            return_value=return_value):
                ctypes.windll = mock_windll
                assert uflash.find_microbit() == 'A:\\' 
Example #17
Source File: test_uflash.py    From uflash with MIT License 6 votes vote down vote up
def test_find_microbit_nt_missing():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'MICROBIT'
    does not exist for a micro:bit device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    with mock.patch('os.name', 'nt'):
        with mock.patch('os.path.exists', return_value=True):
            return_value = ctypes.create_unicode_buffer(1024)
            with mock.patch('ctypes.create_unicode_buffer',
                            return_value=return_value):
                ctypes.windll = mock_windll
                assert uflash.find_microbit() is None 
Example #18
Source File: win.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_physical_ram():
  """Returns the amount of installed RAM in Mb, rounded to the nearest number.
  """

  # https://msdn.microsoft.com/library/windows/desktop/aa366589.aspx
  class MemoryStatusEx(ctypes.Structure):
    _fields_ = [
        ('dwLength', ctypes.c_ulong),
        ('dwMemoryLoad', ctypes.c_ulong),
        ('dwTotalPhys', ctypes.c_ulonglong),
        ('dwAvailPhys', ctypes.c_ulonglong),
        ('dwTotalPageFile', ctypes.c_ulonglong),
        ('dwAvailPageFile', ctypes.c_ulonglong),
        ('dwTotalVirtual', ctypes.c_ulonglong),
        ('dwAvailVirtual', ctypes.c_ulonglong),
        ('dwAvailExtendedVirtual', ctypes.c_ulonglong),
    ]
  stat = MemoryStatusEx()
  stat.dwLength = ctypes.sizeof(MemoryStatusEx)  # pylint: disable=W0201
  ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
  return int(round(stat.dwTotalPhys / 1024. / 1024.)) 
Example #19
Source File: win.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _get_window_class(hwnd):
  """Returns the class name of |hwnd|."""
  ctypes.windll.user32.GetClassNameW.restype = ctypes.c_int
  ctypes.windll.user32.GetClassNameW.argtypes = [
      ctypes.c_void_p,  # HWND
      ctypes.c_wchar_p,
      ctypes.c_int
  ]
  name = ctypes.create_unicode_buffer(257)
  name_len = ctypes.windll.user32.GetClassNameW(hwnd, name, len(name))
  if name_len <= 0 or name_len >= len(name):
    raise ctypes.WinError(descr='GetClassNameW failed; %s' %
                          ctypes.FormatError())
  return name.value


## Public API. 
Example #20
Source File: pyperclip.py    From GDMC with ISC License 6 votes vote down vote up
def _copyWindows(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(None)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #21
Source File: win32_file_watcher_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def test_with_error(self):
    watcher = win32_file_watcher.Win32FileWatcher('/tmp')

    ctypes.windll.kernel32.CreateFileW(
        mox_c('/tmp'),
        mox_c(1L),
        mox_c(3L),
        None,
        mox_c(3L),
        mox_c(win32_file_watcher._FILE_FLAG_BACKUP_SEMANTICS),
        None).AndReturn(win32_file_watcher._INVALID_HANDLE_VALUE)

    self.mox.ReplayAll()
    self.assertRaises(WinError, watcher.start)
    self.mox.VerifyAll() 
Example #22
Source File: defines.py    From pypykatz with MIT License 5 votes vote down vote up
def __init__(self, dllname, funcname):
            self.__dllname = dllname
            self.__funcname = funcname
            self.__func = getattr(getattr(ctypes.windll, dllname), funcname) 
Example #23
Source File: win_inet_pton.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def not_windows():
        raise SystemError(
            "Invalid platform. ctypes.windll must be available."
        ) 
Example #24
Source File: storage.py    From ok-client with Apache License 2.0 5 votes vote down vote up
def replace_transactional(source, destination):
    # Like os.replace, but tries to be actually atomic when possible on Windows.
    if windll:
        error_code = 50  # ERROR_NOT_SUPPORTED
        if windll.ktmw32:
            tx = windll.ktmw32.CreateTransaction(None, None, 0, 0, 0, 0, None)
            if tx != HANDLE(-1).value:
                try: error_code = 0 if windll.kernel32.MoveFileTransactedW(source, destination, windll.kernel32.MoveFileTransactedW.argtypes[2](), None, 0x1 | 0x2, tx) and windll.ktmw32.CommitTransaction(tx) else ctypes.GetLastError()
                finally: windll.kernel32.CloseHandle(tx)
            else: error_code = ctypes.GetLastError()
        if error_code:
            raise ctypes.WinError(error_code)
    else:
        raise NotImplementedError("transactional file systems not supported") 
Example #25
Source File: pyperclip.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def _pasteWindows():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(None)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    data = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return data 
Example #26
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _is_topmost_window(hwnd):
  """Returns True if |hwnd| is a topmost window."""
  ctypes.windll.user32.GetWindowLongW.restype = ctypes.c_long  # LONG
  ctypes.windll.user32.GetWindowLongW.argtypes = [
      ctypes.c_void_p,  # HWND
      ctypes.c_int
  ]
  # -20 is GWL_EXSTYLE
  ex_styles = ctypes.windll.user32.GetWindowLongW(hwnd, -20)
  # 8 is WS_EX_TOPMOST
  return bool(ex_styles & 8) 
Example #27
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _get_disk_info(mount_point):
  """Returns total and free space on a mount point in Mb."""
  total_bytes = ctypes.c_ulonglong(0)
  free_bytes = ctypes.c_ulonglong(0)
  ctypes.windll.kernel32.GetDiskFreeSpaceExW(
      ctypes.c_wchar_p(mount_point), None, ctypes.pointer(total_bytes),
      ctypes.pointer(free_bytes))
  return {
    u'free_mb': round(free_bytes.value / 1024. / 1024., 1),
    u'size_mb': round(total_bytes.value / 1024. / 1024., 1),
  } 
Example #28
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _get_mount_points():
  """Returns the list of 'fixed' drives in format 'X:\\'."""
  ctypes.windll.kernel32.GetDriveTypeW.argtypes = (ctypes.c_wchar_p,)
  ctypes.windll.kernel32.GetDriveTypeW.restype = ctypes.c_ulong
  DRIVE_FIXED = 3
  # https://msdn.microsoft.com/library/windows/desktop/aa364939.aspx
  return [
      u'%s:\\' % letter
      for letter in string.lowercase
      if ctypes.windll.kernel32.GetDriveTypeW(letter + ':\\') == DRIVE_FIXED
  ] 
Example #29
Source File: win_inet_pton.py    From TcpRoute with GNU General Public License v2.0 5 votes vote down vote up
def not_windows():
        raise SystemError(
            "Invalid platform. ctypes.windll must be available."
        ) 
Example #30
Source File: pyperclip.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def _pasteWindows():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(None)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    data = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return data