Python ctypes.wintypes() Examples

The following are 30 code examples of ctypes.wintypes(). 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: pyelastix.py    From pyelastix with MIT License 6 votes vote down vote up
def _is_pid_running_on_windows(pid):
    import ctypes.wintypes
 
    kernel32 = ctypes.windll.kernel32
    handle = kernel32.OpenProcess(1, 0, pid)
    if handle == 0:
        return False
 
    # If the process exited recently, a pid may still exist for the handle.
    # So, check if we can get the exit code.
    exit_code = ctypes.wintypes.DWORD()
    is_running = (
        kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)) == 0)
    kernel32.CloseHandle(handle)
 
    # See if we couldn't get the exit code or the exit code indicates that the
    # process is still running.
    return is_running or exit_code.value == _STILL_ACTIVE


# %% Code for detecting the executables 
Example #2
Source File: __init__.py    From nicewin with GNU General Public License v3.0 6 votes vote down vote up
def get_window_thread_process_id(window_obj):
    """A nice wrapper for GetWindowThreadProcessId(). Returns a tuple of the
    thread id (tid) of the thread that created the specified window, and the
    process id that created the window.

    Syntax:
    DWORD GetWindowThreadProcessId(
      HWND    hWnd,
      LPDWORD lpdwProcessId
    );

    Microsoft Documentation:
    https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid
    """
    pid = wintypes.DWORD()
    tid = ctypes.windll.user32.GetWindowThreadProcessId(window_obj.hWnd, ctypes.byref(pid))
    return tid, pid.value 
Example #3
Source File: driverlib.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def open_sc_manager(machine_name, database_name, desired_access):
	"""See: OpenSCManager function
	https://msdn.microsoft.com/en-us/library/windows/desktop/ms684323(v=vs.85).aspx
	"""
	OpenSCManager_Fn = ctypes.windll.Advapi32.OpenSCManagerA	#SC_HANDLE WINAPI OpenSCManager(
	OpenSCManager_Fn.argtypes = [						#
		LPCTSTR,								#	_In_opt_ LPCTSTR lpMachineName,
		LPCTSTR,								#	_In_opt_ LPCTSTR lpDatabaseName,
		wintypes.DWORD									#	_In_     DWORD   dwDesiredAccess
	]
	OpenSCManager_Fn.restype = wintypes.SC_HANDLE
	handle = OpenSCManager_Fn(
		machine_name,
		database_name,
		desired_access
	)
	return handle 
Example #4
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #5
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 #6
Source File: driverlib.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start_service(service_handle, service_arg_count, service_arg_vectors):
	"""See: StartService function
	https://msdn.microsoft.com/en-us/library/windows/desktop/ms686321(v=vs.85).aspx
	"""
	
	StartService_Fn = ctypes.windll.Advapi32.StartServiceA	#BOOL WINAPI StartService(
	StartService_Fn.argtypes = [					#
		wintypes.SC_HANDLE,							#	_In_ 	 SC_HANDLE hService,
		wintypes.DWORD,								#	_In_ 	 DWORD     dwNumServiceArgs,
		LPCTSTR							#	_In_opt_ LPCTSTR   *lpServiceArgVectors
	]
	StartService_Fn.restype = wintypes.BOOL
	bool = StartService_Fn(
		service_handle,
		service_arg_count, 
		service_arg_vectors
	)
	return bool 
Example #7
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 #8
Source File: registry.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def QueryValueEx(key, value_name):
    """This calls the Windows QueryValueEx function in a Unicode safe way."""
    size = 256
    data_type = ctypes.wintypes.DWORD()
    while True:
        tmp_size = ctypes.wintypes.DWORD(size)
        buf = ctypes.create_string_buffer(size)
        rc = RegQueryValueEx(key.handle, value_name, LPDWORD(),
                             ctypes.byref(data_type), ctypes.cast(buf, LPBYTE),
                             ctypes.byref(tmp_size))
        if rc != ERROR_MORE_DATA:
            break

        # We limit the size here to ~10 MB so the response doesn't get too big.
        if size > 10 * 1024 * 1024:
            raise WindowsError("Value too big to be read.")

        size *= 2

    if rc != ERROR_SUCCESS:
        raise ctypes.WinError(2)

    return (Reg2Py(buf, tmp_size.value, data_type.value), data_type.value) 
Example #9
Source File: link.py    From core with MIT License 6 votes vote down vote up
def _create_windows(source, destination, link_type):
    """Creates hardlink at destination from source in Windows."""

    if link_type == HARDLINK:
        import ctypes
        from ctypes.wintypes import BOOL
        CreateHardLink = ctypes.windll.kernel32.CreateHardLinkW
        CreateHardLink.argtypes = [
            ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p
        ]
        CreateHardLink.restype = BOOL

        res = CreateHardLink(destination, source, None)
        if res == 0:
            raise ctypes.WinError()
    else:
        raise NotImplementedError("Link type unrecognized.") 
Example #10
Source File: faradayftdi.py    From Faraday-Software with GNU General Public License v3.0 6 votes vote down vote up
def PerformStandardReset(self):
        self.Connect()
        self.ResetToggle()
        self.NominalModeToggle()
        self.Disconnect()
        return True

        def SetResetHigh(self):
                ##RESET HIGH TEST LOW
                self.ftd2xxDll.FT_SetBitMode(self.handle, self.BITMASK_IO_OUTPUTS | self.BITMASK_RST, 0x20)

#Action
#BslMode()
#NominalMode()
#NominalForced()
#DisableBsl()

#writeBuffer = ctypes.create_string_buffer("abcdefghijklmnopqrstuvwxyz")
#bytesWritten = ctypes.wintypes.DWORD()
#assert self.ftd2xxDll.FT_Write(self.handle, writeBuffer, len(writeBuffer)-1, ctypes.byref(bytesWritten)) == 0
#print bytesWritten.value 
Example #11
Source File: _pygetwindow_win.py    From PyGetWindow with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _formatMessage(errorCode):
    """A nice wrapper for FormatMessageW(). TODO

    Microsoft Documentation:
    https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessagew

    Additional information:
    https://stackoverflow.com/questions/18905702/python-ctypes-and-mutable-buffers
    https://stackoverflow.com/questions/455434/how-should-i-use-formatmessage-properly-in-c
    """
    lpBuffer = wintypes.LPWSTR()

    ctypes.windll.kernel32.FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
                                          NULL,
                                          errorCode,
                                          0, # dwLanguageId
                                          ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR),
                                          0, # nSize
                                          NULL)
    msg = lpBuffer.value.rstrip()
    ctypes.windll.kernel32.LocalFree(lpBuffer) # Free the memory allocated for the error message's buffer.
    return msg 
Example #12
Source File: microrepl.py    From intellij-micropython with Apache License 2.0 6 votes vote down vote up
def __init__(self) -> None:
        super().__init__()
        # ANSI handling available through SetConsoleMode since Windows 10 v1511
        # https://en.wikipedia.org/wiki/ANSI_escape_code#cite_note-win10th2-1
        if platform.release() == '10' and int(platform.version().split('.')[2]) > 10586:
            ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
            import ctypes.wintypes as wintypes
            if not hasattr(wintypes, 'LPDWORD'):  # PY2
                wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
            SetConsoleMode = ctypes.windll.kernel32.SetConsoleMode
            GetConsoleMode = ctypes.windll.kernel32.GetConsoleMode
            GetStdHandle = ctypes.windll.kernel32.GetStdHandle
            mode = wintypes.DWORD()
            GetConsoleMode(GetStdHandle(-11), ctypes.byref(mode))
            if (mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0:
                SetConsoleMode(GetStdHandle(-11), mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
                self._saved_cm = mode 
Example #13
Source File: support.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #14
Source File: support.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #15
Source File: directoutput.py    From Trade-Dangerous with Mozilla Public License 2.0 6 votes vote down vote up
def Initialize(self, application_name):
        """
        Function to call DirectOutput_Initialize
        
        Required Arguments:
        application_name -- String representing name of applicaiton - must be unique per-application
        
        Returns:
        S_OK: The call completed sucesfully
        E_OUTOFMEMORY: There was insufficient memory to complete this call.
        E_INVALIDARG: The argument is invalid
        E_HANDLE: The DirectOutputManager process could not be found
        
        """
        logging.debug("DirectOutput.Initialize")
        return self.DirectOutputDLL.DirectOutput_Initialize(ctypes.wintypes.LPWSTR(application_name)) 
Example #16
Source File: directoutput.py    From Trade-Dangerous with Mozilla Public License 2.0 6 votes vote down vote up
def SetString(self, device_handle, page, line, string):
        """
        Sets a string to display on the MFD
        
        Required Arguments:
        device_handle -- ID of device
        page -- the ID of the page to add the string to
        line -- the line to display the string on (0 = top, 1 = middle, 2 = bottom)
        string -- the string to display
        
        Returns:
        S_OK: The call completes successfully.
        E_INVALIDARG: The dwPage argument does not reference a valid page id, or the dwString argument does not reference a valid string id.
        E_OUTOFMEMORY: Insufficient memory to complete the request.
        E_HANDLE: The device handle specified is invalid.
        
        """
        logging.debug("DirectOutput.SetString({}, {}, {}, {})".format(device_handle, page, line, string))
        return self.DirectOutputDLL.DirectOutput_SetString(device_handle, page, line, len(string), ctypes.wintypes.LPWSTR(string)) 
Example #17
Source File: support.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #18
Source File: support.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #19
Source File: puppet_util.py    From puppet with MIT License 6 votes vote down vote up
def get_root(key: list =['网上股票交易系统', '通达信']) -> tuple:
    from ctypes.wintypes import BOOL, HWND, LPARAM

    @ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
    def callback(hwnd, lparam):
        user32.GetWindowTextW(hwnd, buf, 64)
        for s in key:
            if s in buf.value:
                handle.value = hwnd
                return False
        return True

    buf = ctypes.create_unicode_buffer(64)
    handle = ctypes.c_ulong()
    user32.EnumWindows(callback)
    return handle.value, buf.value 
Example #20
Source File: support.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #21
Source File: util.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def getWindowsShortPath(path):
    try:
        import ctypes
        import ctypes.wintypes

        ctypes.windll.kernel32.GetShortPathNameW.argtypes = [
            ctypes.wintypes.LPCWSTR,  # lpszLongPath
            ctypes.wintypes.LPWSTR,  # lpszShortPath
            ctypes.wintypes.DWORD  # cchBuffer
        ]
        ctypes.windll.kernel32.GetShortPathNameW.restype = ctypes.wintypes.DWORD

        buf = ctypes.create_unicode_buffer(1024)  # adjust buffer size, if necessary
        ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))

        return buf.value
    except:
        return path 
Example #22
Source File: simple_screen_recorder.py    From Python-tools with MIT License 6 votes vote down vote up
def run(self):
        global EXIT  # 定义全局变量,这个可以在不同线程间共用。

        if not user32.RegisterHotKey(None, id2, 0, win32con.VK_F10):   # 注册快捷键F10并判断是否成功,该热键用于结束程序,且最好这么结束,否则影响下一次注册热键。
            print("Unable to register id", id2)

        # 以下为检测热键是否被按下,并在最后释放快捷键
        try:
            msg = ctypes.wintypes.MSG()
            while True:
                if user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
                    if msg.message == win32con.WM_HOTKEY:
                        if msg.wParam == id2:
                            EXIT=True
                            return
                    user32.TranslateMessage(ctypes.byref(msg))
                    user32.DispatchMessageA(ctypes.byref(msg))
        finally:
            user32.UnregisterHotKey(None, id2)# 必须得释放热键,否则下次就会注册失败,所以当程序异常退出,没有释放热键,
                                              # 那么下次很可能就没办法注册成功了,这时可以换一个热键测试 
Example #23
Source File: playmp3.py    From collection with MIT License 6 votes vote down vote up
def __init__ (self, prefix = ''):
		import ctypes.wintypes
		self.__winmm = ctypes.windll.winmm
		self.__mciSendString = self.__winmm.mciSendStringW
		self.__prefix = prefix
		LPCWSTR = ctypes.wintypes.LPCWSTR
		UINT = ctypes.wintypes.UINT
		HANDLE = ctypes.wintypes.HANDLE
		DWORD = ctypes.wintypes.DWORD
		self.__mciSendString.argtypes = [LPCWSTR, LPCWSTR, UINT, HANDLE]
		self.__mciSendString.restype = ctypes.wintypes.DWORD
		self.__mciGetErrorStringW = self.__winmm.mciGetErrorStringW
		self.__mciGetErrorStringW.argtypes = [DWORD, LPCWSTR, UINT]
		self.__mciGetErrorStringW.restype = ctypes.wintypes.BOOL
		self.__buffer = ctypes.create_unicode_buffer(2048)
		self.__alias_index = 0
		self.__lock = threading.Lock() 
Example #24
Source File: support.py    From blackmamba with MIT License 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #25
Source File: file_path.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def QueryDosDevice(drive_letter):
    """Returns the Windows 'native' path for a DOS drive letter."""
    assert re.match(r'^[a-zA-Z]:$', drive_letter), drive_letter
    assert isinstance(drive_letter, six.text_type)
    # Guesswork. QueryDosDeviceW never returns the required number of bytes.
    chars = 1024
    drive_letter = drive_letter
    p = wintypes.create_unicode_buffer(chars)
    if not windll.kernel32.QueryDosDeviceW(drive_letter, p, chars):
      err = ctypes.GetLastError()
      if err:
        # pylint: disable=undefined-variable
        msg = u'QueryDosDevice(%s): %s (%d)' % (
              drive_letter, FormatError(err), err)
        raise WindowsError(err, msg.encode('utf-8'))
    return p.value 
Example #26
Source File: file_path.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def GetShortPathName(long_path):
    """Returns the Windows short path equivalent for a 'long' path."""
    path = fs.extend(long_path)
    chars = windll.kernel32.GetShortPathNameW(path, None, 0)
    if chars:
      p = wintypes.create_unicode_buffer(chars)
      if windll.kernel32.GetShortPathNameW(path, p, chars):
        return fs.trim(p.value)

    err = ctypes.GetLastError()
    if err:
      # pylint: disable=undefined-variable
      msg = u'GetShortPathName(%s): %s (%d)' % (
            long_path, FormatError(err), err)
      raise WindowsError(err, msg.encode('utf-8'))
    return None 
Example #27
Source File: file_path.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def GetLongPathName(short_path):
    """Returns the Windows long path equivalent for a 'short' path."""
    path = fs.extend(short_path)
    chars = windll.kernel32.GetLongPathNameW(path, None, 0)
    if chars:
      p = wintypes.create_unicode_buffer(chars)
      if windll.kernel32.GetLongPathNameW(path, p, chars):
        return fs.trim(p.value)

    err = ctypes.GetLastError()
    if err:
      # pylint: disable=undefined-variable
      msg = u'GetLongPathName(%s): %s (%d)' % (
            short_path, FormatError(err), err)
      raise WindowsError(err, msg.encode('utf-8'))
    return None 
Example #28
Source File: detectPath.py    From script.service.kodi.callbacks with GNU General Public License v3.0 6 votes vote down vote up
def fsencode(s):
    if sys.platform.lower().startswith('win'):
        try:
            import ctypes
            import ctypes.wintypes
        except ImportError:
            return s
        ctypes.windll.kernel32.GetShortPathNameW.argtypes = [
            ctypes.wintypes.LPCWSTR,  # lpszLongPath
            ctypes.wintypes.LPWSTR,  # lpszShortPath
            ctypes.wintypes.DWORD  # cchBuffer
        ]
        ctypes.windll.kernel32.GetShortPathNameW.restype = ctypes.wintypes.DWORD

        buf = ctypes.create_unicode_buffer(1024)  # adjust buffer size, if necessary
        ctypes.windll.kernel32.GetShortPathNameW(s, buf, len(buf))

        short_path = buf.value
        return short_path
    else:
        return s 
Example #29
Source File: support.py    From jawfish with MIT License 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #30
Source File: windows.py    From goreviewpartner with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        # type: () -> None
        """ Windows initialisations. """

        self.monitorenumproc = ctypes.WINFUNCTYPE(
            ctypes.wintypes.INT,
            ctypes.wintypes.DWORD,
            ctypes.wintypes.DWORD,
            ctypes.POINTER(ctypes.wintypes.RECT),
            ctypes.wintypes.DOUBLE
        )
        set_argtypes(self.monitorenumproc)
        set_restypes()