Python ctypes.wintypes.HANDLE Examples

The following are 30 code examples of ctypes.wintypes.HANDLE(). 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.wintypes , or try the search function .
Example #1
Source File: vcp.py    From monitor_ctrl with MIT License 6 votes vote down vote up
def close(self):
        """
        Close WinAPI Handle.
        
        https://msdn.microsoft.com/en-us/library/windows/desktop/dd692936(v=vs.85).aspx
        BOOL DestroyPhysicalMonitor(
            _In_  HANDLE hMonitor
        );
        :return:
        """
        import ctypes
        api_call = ctypes.windll.Dxva2.DestroyPhysicalMonitor
        
        if not api_call(self._phy_monitor_handle):
            _LOGGER.error(ctypes.WinError())
    
    # ########################## 发送/读取 VCP 设置的函数 
Example #2
Source File: gdbcontroller.py    From pygdbmi with MIT License 6 votes vote down vote up
def _make_non_blocking(file_obj):
    """make file object non-blocking
    Windows doesn't have the fcntl module, but someone on
    stack overflow supplied this code as an answer, and it works
    http://stackoverflow.com/a/34504971/2893090"""

    if USING_WINDOWS:
        LPDWORD = POINTER(DWORD)
        PIPE_NOWAIT = wintypes.DWORD(0x00000001)

        SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
        SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
        SetNamedPipeHandleState.restype = BOOL

        h = msvcrt.get_osfhandle(file_obj.fileno())

        res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
        if res == 0:
            raise ValueError(WinError())

    else:
        # Set the file status flag (F_SETFL) on the pipes to be non-blocking
        # so we can attempt to read from a pipe with no new data without locking
        # the program up
        fcntl.fcntl(file_obj, fcntl.F_SETFL, os.O_NONBLOCK) 
Example #3
Source File: fix_encoding.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def win_handle_is_a_console(handle):
  """Returns True if a Windows file handle is a handle to a console."""
  # These types are available on linux but not Mac.
  # pylint: disable=no-name-in-module,F0401
  from ctypes import byref, POINTER, windll, WINFUNCTYPE
  from ctypes.wintypes import BOOL, DWORD, HANDLE

  FILE_TYPE_CHAR   = 0x0002
  FILE_TYPE_REMOTE = 0x8000
  INVALID_HANDLE_VALUE = DWORD(-1).value

  # <http://msdn.microsoft.com/en-us/library/ms683167.aspx>
  GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
      ('GetConsoleMode', windll.kernel32))
  # <http://msdn.microsoft.com/en-us/library/aa364960.aspx>
  GetFileType = WINFUNCTYPE(DWORD, DWORD)(('GetFileType', windll.kernel32))

  # GetStdHandle returns INVALID_HANDLE_VALUE, NULL, or a valid handle.
  if handle == INVALID_HANDLE_VALUE or handle is None:
    return False
  return (
      (GetFileType(handle) & ~FILE_TYPE_REMOTE) == FILE_TYPE_CHAR and
       GetConsoleMode(handle, byref(DWORD()))) 
Example #4
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanConnect(hClientHandle, pInterfaceGuid, pConnectionParameters):
    """
    The WlanConnect function attempts to connect to a specific network.

    DWORD WINAPI WlanConnect(
            _In_        HANDLE hClientHandle,
            _In_        const GUID *pInterfaceGuid,
            _In_        const PWLAN_CONNECTION_PARAMETERS pConnectionParameters,
            _Reserved_  PVOID pReserved
    );
    """
    func_ref = wlanapi.WlanConnect
    func_ref.argtypes = [HANDLE,
                         POINTER(GUID),
                         POINTER(WLAN_CONNECTION_PARAMETERS),
                         c_void_p]
    func_ref.restype = DWORD
    result = func_ref(hClientHandle,
                      pointer(pInterfaceGuid),
                      pointer(pConnectionParameters),
                      None)
    if result != ERROR_SUCCESS:
        raise Exception("".join(["WlanConnect failed with error ", str(result)]))
    return result 
Example #5
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanDeleteProfile(hClientHandle, pInterfaceGuid, profileName):
    """
    DWORD WINAPI WlanDeleteProfile(
        _In_             HANDLE  hClientHandle,
        _In_       const GUID    *pInterfaceGuid,
        _In_             LPCWSTR strProfileName,
        _Reserved_       PVOID   pReserved
    );
    """
    func_ref = wlanapi.WlanDeleteProfile
    func_ref.argtypes = [HANDLE,
                         POINTER(GUID),
                         LPCWSTR,
                         c_void_p]
    func_ref.restype = DWORD
    result = func_ref(hClientHandle,
                      byref(pInterfaceGuid),
                      profileName,
                      None)
    if result != ERROR_SUCCESS:
        raise Exception("WlanDeleteProfile failed. error %d" % result, result)
    return result 
Example #6
Source File: winapi.py    From hupper with MIT License 6 votes vote down vote up
def DuplicateHandle(
    hSourceProcess,
    hSourceHandle,
    hTargetProcess,
    desiredAccess,
    inheritHandle,
    options,
):
    targetHandle = wintypes.HANDLE()
    ret = kernel32.DuplicateHandle(
        hSourceProcess,
        hSourceHandle,
        hTargetProcess,
        ctypes.byref(targetHandle),
        desiredAccess,
        inheritHandle,
        options,
    )
    CheckError(ret, 'failed to duplicate handle')
    return Handle(targetHandle.value) 
Example #7
Source File: windows10.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_win_vt100_enabled() -> bool:
    """
    Returns True when we're running Windows and VT100 escape sequences are
    supported.
    """
    if not is_windows():
        return False

    hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE))

    # Get original console mode.
    original_mode = DWORD(0)
    windll.kernel32.GetConsoleMode(hconsole, byref(original_mode))

    try:
        # Try to enable VT100 sequences.
        result = windll.kernel32.SetConsoleMode(
            hconsole, DWORD(ENABLE_PROCESSED_INPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
        )

        return result == 1
    finally:
        windll.kernel32.SetConsoleMode(hconsole, original_mode) 
Example #8
Source File: win32.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, stdout: TextIO, use_complete_width: bool = False) -> None:
        self.use_complete_width = use_complete_width

        self._buffer: List[str] = []
        self.stdout = stdout
        self.hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE))

        self._in_alternate_screen = False
        self._hidden = False

        self.color_lookup_table = ColorLookupTable()

        # Remember the default console colors.
        info = self.get_win32_screen_buffer_info()
        self.default_attrs = info.wAttributes if info else 15

        if _DEBUG_RENDER_OUTPUT:
            self.LOG = open(_DEBUG_RENDER_OUTPUT_FILENAME, "ab") 
Example #9
Source File: fix_encoding.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, console_handle, fileno, stream_name, encoding):
    super(WinUnicodeConsoleOutput, self).__init__(
        fileno, '<Unicode console %s>' % stream_name, encoding)
    # Handle to use for WriteConsoleW
    self._console_handle = console_handle

    # Loads the necessary function.
    # These types are available on linux but not Mac.
    # pylint: disable=no-name-in-module,F0401
    from ctypes import byref, GetLastError, POINTER, windll, WINFUNCTYPE
    from ctypes.wintypes import BOOL, DWORD, HANDLE, LPWSTR
    from ctypes.wintypes import LPVOID  # pylint: disable=no-name-in-module

    self._DWORD = DWORD
    self._byref = byref

    # <http://msdn.microsoft.com/en-us/library/ms687401.aspx>
    self._WriteConsoleW = WINFUNCTYPE(
        BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(
            ('WriteConsoleW', windll.kernel32))
    self._GetLastError = GetLastError 
Example #10
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanCloseHandle(hClientHandle):
    """
        The WlanCloseHandle function closes a connection to the server.

        DWORD WINAPI WlanCloseHandle(
            _In_        HANDLE hClientHandle,
            _Reserved_  PVOID pReserved
        );
    """
    func_ref = wlanapi.WlanCloseHandle
    func_ref.argtypes = [HANDLE, c_void_p]
    func_ref.restype = DWORD
    result = func_ref(hClientHandle, None)
    if result != ERROR_SUCCESS:
        raise Exception("WlanCloseHandle failed.")
    return result 
Example #11
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanOpenHandle():
    """
        The WlanOpenHandle function opens a connection to the server.

        DWORD WINAPI WlanOpenHandle(
            _In_        DWORD dwClientVersion,
            _Reserved_  PVOID pReserved,
            _Out_       PDWORD pdwNegotiatedVersion,
            _Out_       PHANDLE phClientHandle
        );
    """
    func_ref = wlanapi.WlanOpenHandle
    func_ref.argtypes = [DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE)]
    func_ref.restype = DWORD
    negotiated_version = DWORD()
    client_handle = HANDLE()
    result = func_ref(2, None, byref(negotiated_version), byref(client_handle))
    if result != ERROR_SUCCESS:
        raise Exception("WlanOpenHandle failed.")
    return client_handle 
Example #12
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanEnumInterfaces(hClientHandle):
    """
        The WlanEnumInterfaces function enumerates all of the wireless LAN
        interfaces currently enabled on the local computer.

        DWORD WINAPI WlanEnumInterfaces(
            _In_        HANDLE hClientHandle,
            _Reserved_  PVOID pReserved,
            _Out_       PWLAN_INTERFACE_INFO_LIST *ppInterfaceList
        );
    """
    func_ref = wlanapi.WlanEnumInterfaces
    func_ref.argtypes = [HANDLE,
                         c_void_p,
                         POINTER(POINTER(WLAN_INTERFACE_INFO_LIST))]
    func_ref.restype = DWORD
    wlan_ifaces = pointer(WLAN_INTERFACE_INFO_LIST())
    result = func_ref(hClientHandle, None, byref(wlan_ifaces))
    if result != ERROR_SUCCESS:
        raise Exception("WlanEnumInterfaces failed.")
    return wlan_ifaces 
Example #13
Source File: driverlib.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def open_service(service_manager_handle, service_name, desired_access):
	""" See: OpenService function
	https://msdn.microsoft.com/en-us/library/windows/desktop/ms684330(v=vs.85).aspx
	"""
	OpenService_Fn = ctypes.windll.Advapi32.OpenServiceA 	#SC_HANDLE WINAPI OpenService(
	OpenService_Fn.argtypes = [						#
		wintypes.HANDLE,							#	_In_ SC_HANDLE hSCManager,
		LPCTSTR,							#	_In_ LPCTSTR   lpServiceName,
		wintypes.DWORD								#	_In_ DWORD     dwDesiredAccess
	]
	OpenService_Fn.restype = wintypes.SC_HANDLE
	handle = OpenService_Fn(
		service_manager_handle,
		service_name,
		desired_access
	)
	return handle 
Example #14
Source File: driverlib.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def open_device(self, access=GENERIC_READ | GENERIC_WRITE, mode=0, creation=OPEN_EXISTING, flags=FILE_ATTRIBUTE_NORMAL):
        """See: CreateFile function
        http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
        """
        CreateFile_Fn = ctypes.windll.kernel32.CreateFileA
        CreateFile_Fn.argtypes = [
                wintypes.LPCSTR,                    # _In_          LPCTSTR lpFileName
                wintypes.DWORD,                     # _In_          DWORD dwDesiredAccess
                wintypes.DWORD,                     # _In_          DWORD dwShareMode
                LPSECURITY_ATTRIBUTES,              # _In_opt_      LPSECURITY_ATTRIBUTES lpSecurityAttributes
                wintypes.DWORD,                     # _In_          DWORD dwCreationDisposition
                wintypes.DWORD,                     # _In_          DWORD dwFlagsAndAttributes
                wintypes.HANDLE]                    # _In_opt_      HANDLE hTemplateFile
        CreateFile_Fn.restype = wintypes.HANDLE

        
        self.handle = wintypes.HANDLE(CreateFile_Fn('\\\\.\\' + self.name,
                             access,
                             mode,
                             NULL,
                             creation,
                             flags,
                             NULL)) 
Example #15
Source File: win32.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def enable_mouse_support(self) -> None:
        ENABLE_MOUSE_INPUT = 0x10
        handle = HANDLE(windll.kernel32.GetStdHandle(STD_INPUT_HANDLE))

        original_mode = DWORD()
        self._winapi(windll.kernel32.GetConsoleMode, handle, pointer(original_mode))
        self._winapi(
            windll.kernel32.SetConsoleMode,
            handle,
            original_mode.value | ENABLE_MOUSE_INPUT,
        ) 
Example #16
Source File: windows10.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, stdout: TextIO) -> None:
        self.win32_output = Win32Output(stdout)
        self.vt100_output = Vt100_Output(stdout, lambda: Size(0, 0))
        self._hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)) 
Example #17
Source File: win32.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def quit_alternate_screen(self) -> None:
        """
        Make stdout again the active buffer.
        """
        if self._in_alternate_screen:
            stdout = HANDLE(
                self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE)
            )
            self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
            self._winapi(windll.kernel32.CloseHandle, self.hconsole)
            self.hconsole = stdout
            self._in_alternate_screen = False 
Example #18
Source File: win32.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_win32_event() -> HANDLE:
    """
    Creates a Win32 unnamed Event .
    http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
    """
    return HANDLE(
        windll.kernel32.CreateEventA(
            pointer(SECURITY_ATTRIBUTES()),
            BOOL(True),  # Manual reset event.
            BOOL(False),  # Initial state.
            None,  # Unnamed event object.
        )
    ) 
Example #19
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def write_process_memory(
    handle: wintypes.HANDLE,
    base_address: wintypes.LPVOID,
    buffer: wintypes.LPCVOID,
    size: ctypes.c_size_t,
    size_ptr: ctypes.POINTER(ctypes.c_size_t),
) -> wintypes.BOOL:
    pass 
Example #20
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def is_wow_64_process_impl(handle: wintypes.HANDLE, bool_ptr: wintypes.PBOOL) -> wintypes.BOOL:
    pass 
Example #21
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def read_process_memory(
    handle: wintypes.HANDLE,
    base_address: wintypes.LPVOID,
    buffer: wintypes.LPCVOID,
    size: ctypes.c_size_t,
    size_ptr: ctypes.POINTER(ctypes.c_size_t),
) -> wintypes.BOOL:
    pass 
Example #22
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def module_first(handle: wintypes.HANDLE, entry_ptr: LPMODULEENTRY32) -> wintypes.BOOL:
    pass 
Example #23
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def close_handle(handle: wintypes.HANDLE) -> wintypes.BOOL:
    pass 
Example #24
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def process_next(handle: wintypes.HANDLE, entry_ptr: LPPROCESSENTRY32) -> wintypes.BOOL:
    pass 
Example #25
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def process_first(handle: wintypes.HANDLE, entry_ptr: LPPROCESSENTRY32) -> wintypes.BOOL:
    pass 
Example #26
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def create_snapshot(flags: wintypes.DWORD, process_id: wintypes.DWORD) -> wintypes.HANDLE:
    pass 
Example #27
Source File: fix_encoding.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
  """Returns a unicode-compatible stream.

  This function will return a direct-Console writing object only if:
  - the file number is the expected console file number
  - the handle the expected file handle
  - the 'real' handle is in fact a handle to a console.
  """
  old_fileno = getattr(stream, 'fileno', lambda: None)()
  if old_fileno == excepted_fileno:
    # These types are available on linux but not Mac.
    # pylint: disable=no-name-in-module,F0401
    from ctypes import windll, WINFUNCTYPE
    from ctypes.wintypes import DWORD, HANDLE

    # <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
    GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))

    real_output_handle = GetStdHandle(DWORD(output_handle))
    if win_handle_is_a_console(real_output_handle):
      # It's a console.
      return WinUnicodeConsoleOutput(
          real_output_handle, old_fileno, stream.name, encoding)

  # It's something else. Create an auto-encoding stream.
  return WinUnicodeOutput(stream, old_fileno, encoding) 
Example #28
Source File: vcp.py    From monitor_ctrl with MIT License 5 votes vote down vote up
def send_vcp_code(self, code: int, value: int) -> bool:
        """
        send vcp code to monitor.
        
        https://msdn.microsoft.com/en-us/library/dd692979(v=vs.85).aspx
        BOOL SetVCPFeature(
            _In_  HANDLE hMonitor,
            _In_  BYTE bVCPCode,
            _In_  DWORD dwNewValue
        );
        
        :param code: VCP Code
        :param value: Data
        :return: Win32 API return
        """
        if code is None:
            _LOGGER.error('vcp code to send is None. ignored.')
            return False
        
        api_call = ctypes.windll.Dxva2.SetVCPFeature
        code = wintypes.BYTE(code)
        new_value = wintypes.DWORD(value)
        api_call.restype = ctypes.c_bool
        ret_ = api_call(self._phy_monitor_handle, code, new_value)
        if not ret_:
            _LOGGER.error('send vcp command failed: ' + hex(code))
            _LOGGER.error(ctypes.WinError())
        return ret_ 
Example #29
Source File: vcp.py    From monitor_ctrl with MIT License 5 votes vote down vote up
def read_vcp_code(self, code: int) -> Tuple[int, int]:
        """
        send vcp code to monitor, get current value and max value.
        
        https://msdn.microsoft.com/en-us/library/dd692953(v=vs.85).aspx
        BOOL GetVCPFeatureAndVCPFeatureReply(
            _In_   HANDLE hMonitor,
            _In_   BYTE bVCPCode,
            _Out_  LPMC_VCP_CODE_TYPE pvct,
            _Out_  LPDWORD pdwCurrentValue,
            _Out_  LPDWORD pdwMaximumValue
        );
        
        :param code: VCP Code
        :return: current_value, max_value
        """
        if code is None:
            _LOGGER.error('vcp code to send is None. ignored.')
            return 0, 0
        
        api_call = ctypes.windll.Dxva2.GetVCPFeatureAndVCPFeatureReply
        api_in_vcp_code = wintypes.BYTE(code)
        api_out_current_value = wintypes.DWORD()
        api_out_max_value = wintypes.DWORD()
        
        if not api_call(self._phy_monitor_handle, api_in_vcp_code, None,
                        ctypes.byref(api_out_current_value), ctypes.byref(api_out_max_value)):
            _LOGGER.error('get vcp command failed: ' + hex(code))
            _LOGGER.error(ctypes.WinError())
        return api_out_current_value.value, api_out_max_value.value 
Example #30
Source File: color.py    From pre-commit with MIT License 5 votes vote down vote up
def _enable() -> None:
        from ctypes import POINTER
        from ctypes import windll
        from ctypes import WinError
        from ctypes import WINFUNCTYPE
        from ctypes.wintypes import BOOL
        from ctypes.wintypes import DWORD
        from ctypes.wintypes import HANDLE

        STD_ERROR_HANDLE = -12
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

        def bool_errcheck(result, func, args):
            if not result:
                raise WinError()
            return args

        GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
            ('GetStdHandle', windll.kernel32), ((1, 'nStdHandle'),),
        )

        GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ('GetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (2, 'lpMode')),
        )
        GetConsoleMode.errcheck = bool_errcheck

        SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
            ('SetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (1, 'dwMode')),
        )
        SetConsoleMode.errcheck = bool_errcheck

        # As of Windows 10, the Windows console supports (some) ANSI escape
        # sequences, but it needs to be enabled using `SetConsoleMode` first.
        #
        # More info on the escape sequences supported:
        # https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
        stderr = GetStdHandle(STD_ERROR_HANDLE)
        flags = GetConsoleMode(stderr)
        SetConsoleMode(stderr, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)