def text_in_coords(query): p = POINT() p.x = query['x'] p.y = query['y'] ret_value = '' hwnd = ctypes.windll.user32.WindowFromPoint(p) if hwnd: get_window_text = '' max_count = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + 5 if max_count > 5: buffer = ctypes.create_unicode_buffer(max_count) ret = ctypes.windll.user32.GetWindowTextW(hwnd, buffer, max_count) if ret > 0: get_window_text = ctypes.wstring_at(buffer) max_count = 1024 buffer = ctypes.create_unicode_buffer(max_count) result = ctypes.windll.user32.GetClassNameW(hwnd, ctypes.pointer(buffer), max_count) if ctypes.wstring_at(buffer) == 'ComboBox': ret_value = {'combobox': {'value': get_window_text, 'values': get_combobox_items(hwnd)}} else: WM_GETTEXT = 0x000d buffer = ctypes.create_unicode_buffer(max_count) length = ctypes.windll.user32.SendMessageW(hwnd, WM_GETTEXT, max_count, ctypes.pointer(buffer)) get_text = ctypes.wstring_at(buffer) if len(get_text) > len(get_window_text): ret_value = get_text else: ret_value = get_window_text return {'status': 'ok', 'text': ret_value}
def open_selector(func, title, filters = [('All Files', ('*.*',))], root = '', multi = False): ofx = OPENFILENAME(0, title, multi) lpstrFile = create_unicode_buffer(root, 1024) ofx.lpstrFile = cast(lpstrFile, c_wchar_p) newFilters = [] for filter in filters: filterTypes = ';'.join(filter[1]) newFilters.append('%s (%s)' % (filter[0], filterTypes)) newFilters.append(filterTypes) filterText = '\x00'.join(newFilters) + "\x00\x00" ofx.lpstrFilter = filterText if func(ctypes.byref(ofx)): if multi: offset = addressof(lpstrFile) items = [] while 1: item = wstring_at(offset) offset += (len(item) + 1) * 2 if item == '': break items.append(item) if len(items) == 1: return items directory = items[0] new_items = [] for item in items[1:]: new_items.append(os.path.join(directory, item)) return new_items else: return wstring_at(addressof(lpstrFile)) return ''
def _build_env(env): """ Builds a unicode environment string for CreateProcessW(), overlaying custom values that the user provided :param env: A dict of unicode strings for a custom environmental variables to set :return: A two-element tuple - [0] None or a byte string to pass to CreateProcessW() - [1] A dict of unicode keys and values, with keys being all uppercase """ str_pointer = kernel32.GetEnvironmentStringsW() system_drive_string = None string = ctypes.wstring_at(str_pointer) existing_env = {} while string != "": # The first entry is the system drive string, which is in a weird # format, so we just copy it since it is required by CreateProcess() if not system_drive_string: system_drive_string = string elif string[0].isalpha(): name, value = string.split("=", 1) existing_env[name.upper()] = value # Include the trailing null byte, and measure each # char as 2 bytes since Windows uses UTF-16 for # wide chars str_pointer += (len(string) + 1) * 2 string = ctypes.wstring_at(str_pointer) if env: for key, value in env.items(): if value is None: if key.upper() in existing_env: del existing_env[key.upper()] else: existing_env[key.upper()] = value env_string = "%s\x00" % system_drive_string for name in sorted(existing_env.keys(), key=lambda s: s.lower()): env_string += "%s=%s\x00" % (name, existing_env[name]) env_string += "\x00" env_bytes = env_string.encode("utf-16le") else: env_bytes = None return env_bytes, existing_env
def _build_env(env): """ Builds a unicode environment string for CreateProcessW(), overlaying custom values that the user provided :param env: A dict of unicode strings for a custom environmental variables to set :return: A two-element tuple - [0] None or a byte string to pass to CreateProcessW() - [1] A dict of unicode keys and values, with keys being all uppercase """ str_pointer = kernel32.GetEnvironmentStringsW() system_drive_string = None string = ctypes.wstring_at(str_pointer) existing_env = {} while string != '': # The first entry is the system drive string, which is in a weird # format, so we just copy it since it is required by CreateProcess() if not system_drive_string: system_drive_string = string elif string[0].isalpha(): name, value = string.split('=', 1) existing_env[name.upper()] = value # Include the trailing null byte, and measure each # char as 2 bytes since Windows uses UTF-16 for # wide chars str_pointer += (len(string) + 1) * 2 string = ctypes.wstring_at(str_pointer) if env: for key, value in env.items(): if value is None: if key.upper() in existing_env: del existing_env[key.upper()] else: existing_env[key.upper()] = value env_string = '%s\x00' % system_drive_string for name in sorted(existing_env.keys(), key=lambda s: s.lower()): env_string += '%s=%s\x00' % (name, existing_env[name]) env_string += '\x00' env_bytes = env_string.encode('utf-16le') else: env_bytes = None return env_bytes, existing_env
def search(self, text, offset=0, max=10): self.reset() if (not self.api.Everything_IsDBLoaded()): print("VE: Failed to load DB, Is Everything running?") return flags = 3 self.api.Everything_SetRequestFlags(flags) self.api.Everything_SetMatchPath(False) self.api.Everything_SetMatchWholeWord(False) self.api.Everything_SetRegex(False) self.api.Everything_SetOffset(offset) self.api.Everything_SetMax(max) self.api.Everything_SetSearchW(text) if (not self.api.Everything_QueryW(True)): print("VE: Failed when trying to Query") self.printEverythingError() return False self.total_results = self.api.Everything_GetTotFileResults() self.num_results = self.api.Everything_GetNumResults() self.file_names = [] self.file_paths = [] self.file_types = [] self.result = [] for i in range(self.num_results): name = self.api.Everything_GetResultFileNameW(i) is_folder = self.api.Everything_IsFolderResult(name) self.file_types.append(is_folder) path = ctypes.create_unicode_buffer(260) self.api.Everything_GetResultFullPathNameW(i, path, 260) name = ctypes.wstring_at(name) path = ctypes.wstring_at(path) name = str(name.encode('utf-8')) path = str(path.encode('utf-8')) path = path.replace("\\", "/") if (not is_folder): path = path[:path.rfind('/')] self.file_names.append(name) self.file_paths.append(path) self.result.append((name, path)) return True
def Reg2Py(data, size, data_type): if data_type == _winreg.REG_DWORD: if size == 0: return 0 return ctypes.cast(data, ctypes.POINTER(ctypes.c_int)).contents.value elif data_type == _winreg.REG_SZ or data_type == _winreg.REG_EXPAND_SZ: return ctypes.wstring_at(data, size // 2).rstrip(u"\x00") elif data_type == _winreg.REG_MULTI_SZ: return ctypes.wstring_at(data, size // 2).rstrip(u"\x00").split(u"\x00") else: if size == 0: return None return ctypes.string_at(data, size)
def read_unicode_from_addr(address, size = None): """read an unicode string from a given pointer to a memory address. The function indirectly uses read_addr() @param address: address where the pointer resides @type address: int @return: unicode string read """ if not address: return unicode("") if size == None: return ctypes.wstring_at(address) return ctypes.wstring_at(address, size)
def read_unicode_from_addr(address, size=None): """read an unicode string from a given pointer to a memory address. The function indirectly uses read_addr() @param address: address where the pointer resides @type address: int @return: unicode string read """ if not address: return unicode("") if size == None: return ctypes.wstring_at(address) return ctypes.wstring_at(address, size)
def _setProductInfo(self): """Set productName and productVersion attributes. """ # Sometimes (I.E. when NVDA starts) handle is 0, so stop if it is the case if not self.processHandle: raise RuntimeError("processHandle is 0") # Choose the right function to use to get the executable file name if winVersion.winVersion.major > 5: # For Windows Vista and higher, use QueryFullProcessImageName function GetModuleFileName = ctypes.windll.Kernel32.QueryFullProcessImageNameW else: GetModuleFileName = ctypes.windll.psapi.GetModuleFileNameExW # Create the buffer to get the executable name exeFileName = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) length = ctypes.wintypes.DWORD(ctypes.wintypes.MAX_PATH) if not GetModuleFileName(self.processHandle, 0, exeFileName, ctypes.byref(length)): raise ctypes.WinError() fileName = exeFileName.value # Get size needed for buffer (0 if no info) size = ctypes.windll.version.GetFileVersionInfoSizeW(fileName, None) if not size: raise RuntimeError("No version information") # Create buffer res = ctypes.create_string_buffer(size) # Load file informations into buffer res ctypes.windll.version.GetFileVersionInfoW(fileName, None, size, res) r = ctypes.c_uint() l = ctypes.c_uint() # Look for codepages ctypes.windll.version.VerQueryValueW(res, u'\\VarFileInfo\\Translation', ctypes.byref(r), ctypes.byref(l)) if not l.value: raise RuntimeError("No codepage") # Take the first codepage (what else ?) codepage = array.array('H', ctypes.string_at(r.value, 4)) codepage = "%04x%04x" % tuple(codepage) # Extract product name and put it to self.productName ctypes.windll.version.VerQueryValueW( res, u'\\StringFileInfo\\%s\\ProductName' % codepage, ctypes.byref(r), ctypes.byref(l)) self.productName = ctypes.wstring_at(r.value, l.value - 1) # Extract product version and put it to self.productVersion ctypes.windll.version.VerQueryValueW( res, u'\\StringFileInfo\\%s\\ProductVersion' % codepage, ctypes.byref(r), ctypes.byref(l)) self.productVersion = ctypes.wstring_at(r.value, l.value - 1)
def get_performance_info(self): pi= self._osmodule.getPerformanceInfo() s="" if pi: s = ctypes.wstring_at(pi) self._osmodule.freeMemory(pi) return json.loads(s)
def get_cdrom_drive_mount_point(self): mount_point = None buf = ctypes.create_unicode_buffer(2048) buf_len = kernel32.GetLogicalDriveStringsW( ctypes.sizeof(buf) / ctypes.sizeof(wintypes.WCHAR), buf) if not buf_len: raise exception.CloudbaseInitException( "Cannot enumerate logical devices") cdrom_dev = self.get_physical_path().rsplit('\\')[-1].upper() i = 0 while not mount_point and i < buf_len: curr_drive = ctypes.wstring_at(ctypes.addressof(buf) + i * ctypes.sizeof(wintypes.WCHAR))[:-1] dev = ctypes.create_unicode_buffer(2048) ret_val = kernel32.QueryDosDeviceW(curr_drive, dev, ctypes.sizeof(dev) / ctypes.sizeof(wintypes.WCHAR)) if not ret_val: raise exception.CloudbaseInitException( "Cannot query NT device") if dev.value.rsplit('\\')[-1].upper() == cdrom_dev: mount_point = curr_drive else: i += len(curr_drive) + 2 return mount_point
def get_app_id(): mem = ctypes.POINTER(ctypes.c_wchar)() ctypes.windll.shell32.GetCurrentProcessExplicitAppUserModelID( ctypes.byref(mem)) res = ctypes.wstring_at(mem) ctypes.windll.Ole32.CoTaskMemFree(mem) return res
def _decode_surrogatepass(data, codec): """Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work on Python < 3.4 + Windows https://bugs.python.org/issue27971 Raises UnicodeDecodeError, LookupError """ try: return data.decode(codec, _surrogatepass) except UnicodeDecodeError: if not _codec_can_decode_with_surrogatepass(codec): if _normalize_codec(codec) == "utf-16-be": data = _swap_bytes(data) codec = "utf-16-le" if _normalize_codec(codec) == "utf-16-le": buffer_ = ctypes.create_string_buffer(data + b"\x00\x00") value = ctypes.wstring_at(buffer_, len(data) // 2) if value.encode("utf-16-le", _surrogatepass) != data: raise return value else: raise else: raise
def OnCopyData(self, hwnd, msg, wparam, lparam): pCDS = ctypes.cast(lparam, PCOPYDATASTRUCT) command = hex(pCDS.contents.dwData) data = ctypes.wstring_at(pCDS.contents.lpData) print command, data self.do_stuff(command, data)
def get_device_interface_detail_data(dev_list, p_interface_data, buf=None): if buf is None: buf = create_string_buffer(512) detail = cast(buf, PSP_DEVICE_INTERFACE_DETAIL_DATA) # See http://stackoverflow.com/questions/10728644/properly-declare-sp-device-interface-detail-data-for-pinvoke # for why cbSize needs to be hardcoded below detail.contents.cbSize = 8 if is64bit else 6 required_size = DWORD(0) devinfo = SP_DEVINFO_DATA() devinfo.cbSize = sizeof(devinfo) while True: if not SetupDiGetDeviceInterfaceDetail( dev_list, p_interface_data, detail, len(buf), byref(required_size), byref(devinfo)): err = get_last_error() if err == ERROR_INSUFFICIENT_BUFFER: buf = create_string_buffer(required_size.value + 50) detail = cast(buf, PSP_DEVICE_INTERFACE_DETAIL_DATA) detail.contents.cbSize = 8 if is64bit else 6 continue raise WinError(err) break return buf, devinfo, wstring_at( addressof(buf) + sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA._fields_[0][1]))
def getFileVersionInfo(name, *attributes): """Gets the specified file version info attributes from the provided file.""" if not isinstance(name, text_type): raise TypeError("name must be an unicode string") if not os.path.exists(name): raise RuntimeError("The file %s does not exist" % name) fileVersionInfo = {} # Get size needed for buffer (0 if no info) size = ctypes.windll.version.GetFileVersionInfoSizeW(name, None) if not size: raise RuntimeError("No version information") # Create buffer res = ctypes.create_string_buffer(size) # Load file informations into buffer res ctypes.windll.version.GetFileVersionInfoW(name, None, size, res) r = ctypes.c_uint() l = ctypes.c_uint() # Look for codepages ctypes.windll.version.VerQueryValueW(res, u'\\VarFileInfo\\Translation', ctypes.byref(r), ctypes.byref(l)) if not l.value: raise RuntimeError("No codepage") # Take the first codepage (what else ?) codepage = array.array('H', ctypes.string_at(r.value, 4)) codepage = "%04x%04x" % tuple(codepage) for attr in attributes: if not ctypes.windll.version.VerQueryValueW(res, u'\\StringFileInfo\\%s\\%s' % (codepage, attr), ctypes.byref(r), ctypes.byref(l) ): log.warning("Invalid or unavailable version info attribute for %r: %s" % (name, attr)) fileVersionInfo[attr] = None else: fileVersionInfo[attr] = ctypes.wstring_at(r.value, l.value-1) return fileVersionInfo
def _UnpackDEV_BROADCAST(lparam): """ Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be used for monkey-patching said module with correct handling of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE """ import ctypes if lparam == 0: return None hdr_format = "iii" hdr_size = struct.calcsize(hdr_format) hdr_buf = win32gui.PyGetMemory(lparam, hdr_size) size, devtype, reserved = struct.unpack("iii", hdr_buf) # Due to x64 alignment issues, we need to use the full format string over # the entire buffer. ie, on x64: # calcsize('iiiP') != calcsize('iii')+calcsize('P') buf = win32gui.PyGetMemory(lparam, size) extra = {} if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE: fmt = hdr_format + "16s" _, _, _, guid_bytes = struct.unpack(fmt, buf[:struct.calcsize(fmt)]) extra['classguid'] = pywintypes.IID(guid_bytes, True) extra['name'] = ctypes.wstring_at(lparam + struct.calcsize(fmt)) else: raise NotImplementedError("unknown device type %d" % (devtype,)) return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
def OnCopyData(self, hwnd, msg, wparam, lparam): # for debug # print("--> Received some message from Jupiter:") # print(hwnd) # print(msg) # print(wparam) # print(lparam) # print(pCDS.contents.dwData) # print(pCDS.contents.cbData) # for debug pCDS = ctypes.cast(lparam, PSHARED_MEMORY) msg = ctypes.wstring_at(pCDS.contents.lpData) if pCDS.contents.dwData != WM_DATA_JUPITER_INDEX: print("[Error] This is not a message from Jupiter") return pass global trimMsg trimMsg = ''.join(filter(lambda x: ord(x) < 128, msg)) trimMsg = trimMsg.replace('64)]', '') # JupiterMessageHandler(trimMsg) return 1
def get_system_info(self): pi= self._osmodule.getSystemInfo() s="" if pi: s = ctypes.wstring_at(pi) self._osmodule.freeMemory(pi) return json.loads(s)
def to_unichr(vk, sc, ss): fill_state(ss) rc = ToUnicodeEx(vk, sc, state, strbuf, len(strbuf), 0, layout_id) if rc > 0: dead_key = False char = ctypes.wstring_at(strbuf.value, rc) elif rc < 0: # Dead key, flush state. dead_key = True fill_state(0) rc = ToUnicodeEx(VK.SPACE, vk_to_sc[VK.SPACE], state, strbuf, len(strbuf), 0, layout_id) char = ctypes.wstring_at(strbuf.value, rc) if rc > 0 else "" else: dead_key = False char = "" return char, dead_key
def get_cdrom_drive_mount_point(self): mount_point = None buf = ctypes.create_unicode_buffer(2048) buf_len = kernel32.GetLogicalDriveStringsW(ctypes.sizeof(buf) / ctypes.sizeof(wintypes.WCHAR), buf) if not buf_len: raise Exception("Cannot enumerate logical devices") cdrom_dev = self.get_physical_path().rsplit("\\")[-1].upper() i = 0 while not mount_point and i < buf_len: curr_drive = ctypes.wstring_at(ctypes.addressof(buf) + i * ctypes.sizeof(wintypes.WCHAR))[:-1] dev = ctypes.create_unicode_buffer(2048) ret_val = kernel32.QueryDosDeviceW(curr_drive, dev, ctypes.sizeof(dev) / ctypes.sizeof(wintypes.WCHAR)) if not ret_val: raise Exception("Cannot query NT device") if dev.value.rsplit("\\")[-1].upper() == cdrom_dev: mount_point = curr_drive else: i += len(curr_drive) + 2 return mount_point
def _helper(self, method, path): ucs2_string_ptr = check_error_value(call(method, ctypes.addressof(path), 0, 0)) try: s = ctypes.wstring_at(ucs2_string_ptr) finally: check_status(call(system_table.BootServices.contents.FreePool, ucs2_string_ptr)) return s
def get_symbolic_target(handle): data_buff = get_reparse_point(handle) offset = REPARSE_DATA_BUFFER.ReparseBuffer.offset + \ SymbolicLinkReparseBuffer.PathBuffer.offset + \ data_buff.ReparseBuffer.SymbolicLink.PrintNameOffset - 2 * ctypes.sizeof(ctypes.c_wchar) return wstring_at(byref(data_buff, offset), data_buff.ReparseBuffer.SymbolicLink.PrintNameLength/ctypes.sizeof(ctypes.c_wchar))
def FromTableauString(ts): """Convert a C TableauString to a Python string""" tslen = common_lib.TableauStringLength(ts) buffer = ctypes.create_string_buffer((tslen + 1) * ctypes.sizeof(ctypes.c_wchar)) common_lib.FromTableauString(ts, ctypes.byref(buffer)) return ctypes.wstring_at(buffer, tslen)
def newDevAttrFunc(device, descriptor): oldDevAttrFunc(device, descriptor) buf_ser = ctypes.create_string_buffer(1024) result = fido2._pyu2f.windows.hid.HidD_GetSerialNumberString( device, buf_ser, 1024) if result: descriptor.serial_number = ctypes.wstring_at(buf_ser)
def open_selector(func, title, filters=[('All Files', ('*.*', ))], root='', multi=False): ofx = OPENFILENAME(0, title, multi) lpstrFile = create_unicode_buffer(root, 1024) ofx.lpstrFile = cast(lpstrFile, c_wchar_p) newFilters = [] for filter in filters: filterTypes = ';'.join(filter[1]) newFilters.append('%s (%s)' % (filter[0], filterTypes)) newFilters.append(filterTypes) filterText = '\x00'.join(newFilters) + "\x00\x00" ofx.lpstrFilter = filterText print 'doing it' if func(ctypes.byref(ofx)): if multi: '%r' % ofx.lpstrFile print string_at(addressof(lpstrFile), 1024) offset = addressof(lpstrFile) print offset items = [] while 1: item = wstring_at(offset) offset += len(item) if item == '': break items.append(item) return items else: return ofx.lpstrFile.replace("\0", "") return ''
def watcher(path, restart): the_dir = CreateFile(path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, None ) buffer = ctypes.create_string_buffer(32 * 1024) bytes_ret = ctypes.c_uint32() while ReadDirectoryChangesW(the_dir, buffer, ctypes.sizeof(buffer), True, FILE_NOTIFY_CHANGE_LAST_WRITE, ctypes.byref(bytes_ret), None, None): cur_pointer = ctypes.addressof(buffer) while True: fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) filename = ctypes.wstring_at(cur_pointer + 12) if restart.match(filename): log('wfastcgi.py exiting because ' + filename + ' has changed, matching ' + restartRegex + '\n') # we call ExitProcess directly to quickly shutdown the whole process # because sys.exit(0) won't have an effect on the main thread. ExitProcess(0) if fni.contents.NextEntryOffset == 0: break cur_pointer = cur_pointer + fni.contents.NextEntryOffset
def scan(top_path): prefix_len = len(top_path.rstrip(os.sep)) + 1 if os.name == 'nt': if ':' in top_path: prefix_len -= 1 # backslash after drive letter and colon is missing under windows # setup search everything_dll.Everything_SetSearchW(f'"{top_path}"') everything_dll.Everything_SetRequestFlags(EVERYTHING_REQUEST_FILE_NAME | EVERYTHING_REQUEST_PATH | EVERYTHING_REQUEST_SIZE) # execute the query everything_dll.Everything_QueryW(1) # get the number of results num_results = everything_dll.Everything_GetNumResults() # create buffers filename = ctypes.create_unicode_buffer(260) file_size = ctypes.c_ulonglong(1) directory_size = 2**64 - 1 # show results for i in range(num_results): everything_dll.Everything_GetResultFullPathNameW(i, filename, 260) everything_dll.Everything_GetResultSize(i, file_size) if file_size.value == directory_size: # no way to judge if it's a directory continue yield ctypes.wstring_at(filename)[prefix_len:], file_size.value
def get_link_target(path): """Takes a path to a .lnk file and returns a path the .lnk file is targeting. Might raise WindowsError in case something fails. """ assert isinstance(path, str) CoInitialize(None) pShellLinkW = IShellLinkW() CoCreateInstance(ctypes.byref(CLSID_ShellLink), None, CLSCTX_INPROC_SERVER, ctypes.byref(IShellLinkW.IID), ctypes.byref(pShellLinkW)) try: pPersistFile = IPersistFile() pShellLinkW.QueryInterface(ctypes.byref(IPersistFile.IID), ctypes.byref(pPersistFile)) try: buffer_ = ctypes.create_unicode_buffer(path, MAX_PATH) pPersistFile.Load(buffer_, 0) finally: pPersistFile.Release() pShellLinkW.GetPath(buffer_, MAX_PATH, None, 0) finally: pShellLinkW.Release() return ctypes.wstring_at(buffer_)
def window_text(hwnd: int) -> str: """Collect the text of a window element.""" text = ctypes.create_unicode_buffer(LARGE_BUFFER) length = ctypes.windll.user32.GetWindowTextW(hwnd, text, LARGE_BUFFER) wstring = ctypes.wstring_at(text, length) return wstring.replace('\00', ' ').strip() if length > 0 else ''
def FillDeviceAttributes(device, descriptor): """Fill out the attributes of the device. Fills the devices HidAttributes and product string into the descriptor. Args: device: A handle to the open device descriptor: The DeviceDescriptor to populate with the attributes. Returns: None Raises: WindowsError when unable to obtain attributes or product string. """ attributes = HidAttributes() result = hid.HidD_GetAttributes(device, ctypes.byref(attributes)) if not result: raise ctypes.WinError() buf = ctypes.create_string_buffer(1024) result = hid.HidD_GetProductString(device, buf, 1024) if not result: raise ctypes.WinError() descriptor.vendor_id = attributes.VendorID descriptor.product_id = attributes.ProductID descriptor.product_string = ctypes.wstring_at(buf)
def getResult(self, searchStr): '''result是一个Tuple Set''' self.setupSearch(searchStr) # self.everything_dll.Everything_SetRequestFlags(77) self.executeSearch() self.getNumResult() num = self.num_results if self.num_results > 3000: #大于3000条则只取3000条 num = 3000 else: num = self.num_results self.createBuffers() result = set() for i in range(num): self.everything_dll.Everything_GetResultFullPathNameW( i, self.filename, 260) self.everything_dll.Everything_GetResultDateModified( i, self.date_modified_filetime) self.everything_dll.Everything_GetResultSize(i, self.file_size) if self.file_size.value == 18446744073709551615: self.file_size.value = 0 fullName = format(ctypes.wstring_at(self.filename)) d = (fullName, str(self.file_size.value), self.get_time(self.date_modified_filetime)) result.add(d) # d={"FileName":fileName,"FileDir":fileDir,"DateModified":self.get_time(self.date_modified_filetime),"FileSize":self.file_size.value} return result
def get_window_text(self, hwnd): ''' Returns the associated window text as per windows API ''' max_count = 38911 text_buffer = ctypes.create_unicode_buffer(max_count) length = ctypes.windll.user32.GetWindowTextW(hwnd, text_buffer, max_count) if length > 0 and length != 38911: return ctypes.wstring_at(text_buffer) elif length == 38911: max_count = 122365 text_buffer = ctypes.create_unicode_buffer(max_count) ctypes.windll.user32.GetWindowTextW(hwnd, text_buffer, max_count) return ctypes.wstring_at(text_buffer) return ''
def _bytes2winpath(data, codec): """Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work on Python < 3.4 + Windows https://bugs.python.org/issue27971 Raises UnicodeDecodeError, LookupError """ try: return data.decode(codec, _surrogatepass) except UnicodeDecodeError: if not _codec_can_decode_with_surrogatepass(codec): if _normalize_codec(codec) == "utf-16-be": data = _swap_bytes(data) codec = "utf-16-le" if _normalize_codec(codec) == "utf-16-le": buffer_ = ctypes.create_string_buffer(data + b"\x00\x00") value = ctypes.wstring_at(buffer_, len(data) // 2) if value.encode("utf-16-le", _surrogatepass) != data: raise return value else: raise else: raise
def open_selector(func, title, filters = [('All Files', ('*.*',))], root = '', multi = False): ofx = OPENFILENAME(0, title, multi) lpstrFile = create_unicode_buffer(root, 1024) ofx.lpstrFile = cast(lpstrFile, c_wchar_p) newFilters = [] for filter in filters: filterTypes = ';'.join(filter[1]) newFilters.append('%s (%s)' % (filter[0], filterTypes)) newFilters.append(filterTypes) filterText = '\x00'.join(newFilters) + "\x00\x00" ofx.lpstrFilter = filterText print 'doing it' if func(ctypes.byref(ofx)): if multi: '%r' % ofx.lpstrFile print string_at(addressof(lpstrFile), 1024) offset = addressof(lpstrFile) print offset items = [] while 1: item = wstring_at(offset) offset += len(item) if item == '': break items.append(item) return items else: return ofx.lpstrFile.replace("\0", "") return ''
def get_window_wm_text(self, hwnd): ''' Returns the text as per window WM_GETTEXT ''' max_count = 38911 text_buffer = ctypes.create_unicode_buffer(max_count) length = ctypes.windll.user32.SendMessageW(hwnd, WM_GETTEXT, max_count, ctypes.pointer(text_buffer)) if length != 38911: return ctypes.wstring_at(text_buffer) else: max_count = 122365 text_buffer = ctypes.create_unicode_buffer(max_count) length = ctypes.windll.user32.SendMessageW( hwnd, WM_GETTEXT, max_count, ctypes.pointer(text_buffer)) return ctypes.wstring_at(text_buffer)
def get_service_list(self): pi= self._osmodule.getServiceList() s="" if pi: s = ctypes.wstring_at(pi) self._osmodule.freeMemory(pi) return json.loads(s)
def watch(h): log("Watching events ...") buffer = ctypes.create_unicode_buffer(1024) lpBytesReturned = ctypes.c_ulong() while True: results = ctypes.windll.kernel32.ReadDirectoryChangesW( h, buffer, 1024, True, 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_LAST_ACCESS | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, ctypes.byref(lpBytesReturned), None, None) if results == 0: log("Error 0x%08x : Unable to read directory changes" % ctypes.GetLastError()) break else: toSkip = 0 while lpBytesReturned.value > 0: pEntry = ctypes.cast( ctypes.addressof(buffer) + toSkip, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) toSkip = pEntry[0].NextEntryOffset name = ctypes.wstring_at( ctypes.addressof(pEntry[0]) + FILE_NOTIFY_INFORMATION.FileName.offset, pEntry[0].FileNameLength >> 1) log("%s %s : %s" % ("Directory" if os.path.isdir(name) else "File", CHANGES[pEntry[0].Action], name)) if toSkip == 0: break lpBytesReturned.value -= toSkip
def get_link_target(path): """Takes a path to a .lnk file and returns a path the .lnk file is targeting. Might raise WindowsError in case something fails. """ assert isinstance(path, text_type) CoInitialize(None) pShellLinkW = IShellLinkW() CoCreateInstance( ctypes.byref(CLSID_ShellLink), None, CLSCTX_INPROC_SERVER, ctypes.byref(IShellLinkW.IID), ctypes.byref(pShellLinkW)) try: pPersistFile = IPersistFile() pShellLinkW.QueryInterface(ctypes.byref(IPersistFile.IID), ctypes.byref(pPersistFile)) try: buffer_ = ctypes.create_unicode_buffer(path, MAX_PATH) pPersistFile.Load(buffer_, 0) finally: pPersistFile.Release() pShellLinkW.GetPath(buffer_, MAX_PATH, None, 0) finally: pShellLinkW.Release() return ctypes.wstring_at(buffer_)
def _Reg2Py(data, size, data_type): """Converts a Windows Registry value to the corresponding Python data type.""" if data_type == winreg.REG_DWORD: if size == 0: return 0 # DWORD is an unsigned 32-bit integer, see: # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/262627d8-3418-4627-9218-4ffe110850b2 return ctypes.cast(data, ctypes.POINTER(ctypes.c_uint32)).contents.value elif data_type == winreg.REG_SZ or data_type == winreg.REG_EXPAND_SZ: return ctypes.wstring_at(data, size // 2).rstrip(u"\x00") elif data_type == winreg.REG_MULTI_SZ: return ctypes.wstring_at(data, size // 2).rstrip(u"\x00").split(u"\x00") else: if size == 0: return None return ctypes.string_at(data, size)
def watcher(path, restart): the_dir = CreateFile( path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, None) buffer = ctypes.create_string_buffer(32 * 1024) bytes_ret = ctypes.c_uint32() while ReadDirectoryChangesW(the_dir, buffer, ctypes.sizeof(buffer), True, FILE_NOTIFY_CHANGE_LAST_WRITE, ctypes.byref(bytes_ret), None, None): cur_pointer = ctypes.addressof(buffer) while True: fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) filename = ctypes.wstring_at(cur_pointer + 12) if restart.match(filename): log('wfastcgi.py exiting because ' + filename + ' has changed, matching ' + restartRegex + '\n') # we call ExitProcess directly to quickly shutdown the whole process # because sys.exit(0) won't have an effect on the main thread. ExitProcess(0) if fni.contents.NextEntryOffset == 0: break cur_pointer = cur_pointer + fni.contents.NextEntryOffset
def GWFileConfigGet(self): """Retrieves the current XML content management configuration from the Glasswall library. :return: A result indicating the status of the call along with the XML content management configuration. :rtype: GwConfigReturnObj """ # API function declaration self.gwLibrary.GWFileConfigGet.argtypes = [ ct.POINTER(ct.POINTER(ct.c_wchar)), ct.POINTER(ct.c_size_t) ] # Variable initialisation ct_configurationBuffer = ct.POINTER(ct.c_wchar)() ct_size = ct.c_size_t(0) # Return Object gwReturn = GwConfigReturnObj() # API Call gwReturn.returnStatus = self.gwLibrary.GWFileConfigGet( ct.byref(ct_configurationBuffer), ct.byref(ct_size)) # Convert outputBuffer to python string gwReturn.string = ct.wstring_at(ct_configurationBuffer) return gwReturn
def enum_changes(path): """Returns a generator that blocks until a change occurs, then yields the filename of the changed file. Yields an empty string and stops if the buffer overruns, indicating that too many files were changed.""" buffer = ctypes.create_string_buffer(32 * 1024) bytes_ret = ctypes.c_uint32() try: the_dir = CreateFile( path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0, ) except OSError: maybe_log("Unable to create watcher") return if not the_dir or the_dir == INVALID_HANDLE_VALUE: maybe_log("Unable to create watcher") return while True: ret_code = ReadDirectoryChangesW( the_dir, buffer, ctypes.sizeof(buffer), True, FILE_NOTIFY_CHANGE_LAST_WRITE, ctypes.byref(bytes_ret), None, None, ) if ret_code: cur_pointer = ctypes.addressof(buffer) while True: fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) # FileName is not null-terminated, so specifying length is mandatory. filename = ctypes.wstring_at( cur_pointer + 12, fni.contents.FileNameLength // 2) yield filename if fni.contents.NextEntryOffset == 0: break cur_pointer = cur_pointer + fni.contents.NextEntryOffset elif GetLastError() == ERROR_NOTIFY_ENUM_DIR: CloseHandle(the_dir) yield '' return else: CloseHandle(the_dir) return
def _setProductInfo(self): """Set productName and productVersion attributes. """ # Sometimes (I.E. when NVDA starts) handle is 0, so stop if it is the case if not self.processHandle: raise RuntimeError("processHandle is 0") # Choose the right function to use to get the executable file name if winVersion.winVersion.major > 5: # For Windows Vista and higher, use QueryFullProcessImageName function GetModuleFileName = ctypes.windll.Kernel32.QueryFullProcessImageNameW else: GetModuleFileName = ctypes.windll.psapi.GetModuleFileNameExW # Create the buffer to get the executable name exeFileName = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) length = ctypes.wintypes.DWORD(ctypes.wintypes.MAX_PATH) if not GetModuleFileName(self.processHandle, 0, exeFileName, ctypes.byref(length)): raise ctypes.WinError() fileName = exeFileName.value # Get size needed for buffer (0 if no info) size = ctypes.windll.version.GetFileVersionInfoSizeW(fileName, None) if not size: raise RuntimeError("No version information") # Create buffer res = ctypes.create_string_buffer(size) # Load file informations into buffer res ctypes.windll.version.GetFileVersionInfoW(fileName, None, size, res) r = ctypes.c_uint() l = ctypes.c_uint() # Look for codepages ctypes.windll.version.VerQueryValueW(res, u'\\VarFileInfo\\Translation', ctypes.byref(r), ctypes.byref(l)) if not l.value: raise RuntimeError("No codepage") # Take the first codepage (what else ?) codepage = array.array('H', ctypes.string_at(r.value, 4)) codepage = "%04x%04x" % tuple(codepage) # Extract product name and put it to self.productName ctypes.windll.version.VerQueryValueW(res, u'\\StringFileInfo\\%s\\ProductName' % codepage, ctypes.byref(r), ctypes.byref(l)) self.productName = ctypes.wstring_at(r.value, l.value-1) # Extract product version and put it to self.productVersion ctypes.windll.version.VerQueryValueW(res, u'\\StringFileInfo\\%s\\ProductVersion' % codepage, ctypes.byref(r), ctypes.byref(l)) self.productVersion = ctypes.wstring_at(r.value, l.value-1)
def wszarray_to_list(array): offset = 0 while offset < len(array): sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2) if sz: yield sz offset += len(sz)+1 else: break
def enum_changes(path): """Returns a generator that blocks until a change occurs, then yields the filename of the changed file. Yields an empty string and stops if the buffer overruns, indicating that too many files were changed.""" buffer = ctypes.create_string_buffer(32 * 1024) bytes_ret = ctypes.c_uint32() try: the_dir = CreateFile( path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0, ) except OSError: maybe_log("Unable to create watcher") return if not the_dir or the_dir == INVALID_HANDLE_VALUE: maybe_log("Unable to create watcher") return while True: ret_code = ReadDirectoryChangesW( the_dir, buffer, ctypes.sizeof(buffer), True, FILE_NOTIFY_CHANGE_LAST_WRITE, ctypes.byref(bytes_ret), None, None, ) if ret_code: cur_pointer = ctypes.addressof(buffer) while True: fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) # FileName is not null-terminated, so specifying length is mandatory. filename = ctypes.wstring_at(cur_pointer + 12, fni.contents.FileNameLength // 2) yield filename if fni.contents.NextEntryOffset == 0: break cur_pointer = cur_pointer + fni.contents.NextEntryOffset elif GetLastError() == ERROR_NOTIFY_ENUM_DIR: CloseHandle(the_dir) yield '' return else: CloseHandle(the_dir) return
def _getinfo(self): info = MONITORINFOEX() info.cbSize = MONITORINFOEX_size if not GetMonitorInfo(self.hmonitor, byref(info)): raise WinError() self._clientarea = wxRectFromRECT(info.rcWork) self._geometry = wxRectFromRECT(info.rcMonitor) self._deviceid = wstring_at(info.szDevice)
def GetShortPathName(path): import ctypes nsize = 2048 out = ctypes.create_unicode_buffer(nsize) short = None if ctypes.windll.kernel32.GetShortPathNameW(path, ctypes.pointer(out), nsize): return ctypes.wstring_at(path) else: print(ctypes.windll.kernel32.GetLastError())
def get_active_window_class(query): hWnd = ctypes.windll.user32.GetForegroundWindow() max_count = 1024 buffer = ctypes.create_unicode_buffer(max_count) result = ctypes.windll.user32.GetClassNameW(hWnd, ctypes.pointer(buffer), max_count) if result == 0: return {'status': 'fail', 'message': 'Failed to get window class'} else: return {'status': 'ok', 'name': ctypes.wstring_at(buffer)}
def get_volume_mount_points(self, volume_guid): if not volume_guid.endswith('\\'): volume_guid = u"{}\\".format(volume_guid) volumePathNames = create_unicode_buffer(MAX_PATH_NAMES) returnLength = DWORD(0) GetVolumePathNamesForVolumeNameW(volumeName=volume_guid, volumePathNames=volumePathNames, returnLength=returnLength) return filter(lambda string: string != u'', ctypes.wstring_at(ctypes.addressof(volumePathNames), returnLength.value).split(u"\x00"))
def _sh_get_known_folder_path_result_handler(result, func, args): if result == S_OK: try: path_ptr = args[3] return ctypes.wstring_at(path_ptr) finally: CoTaskMemFree(path_ptr) else: return args
def GetDevicePaths(): classGuid = GUID() CLSIDFromString(DRIVER_CLASS_GUID, byref(classGuid)) hDevInfo = SetupDiGetClassDevs( classGuid, None, None, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE ) if hDevInfo == INVALID_HANDLE_VALUE: raise WinError() deviceInterfaceData = SP_DEVICE_INTERFACE_DATA() deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA) deviceInfoData = SP_DEVINFO_DATA() deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA) memberIndex = 0 result = {} while True: if not SetupDiEnumDeviceInterfaces( hDevInfo, None, classGuid, memberIndex, byref(deviceInterfaceData) ): err = GetLastError() if err == ERROR_NO_MORE_ITEMS: break else: raise WinError(err) requiredSize = DWORD() SetupDiGetDeviceInterfaceDetail( hDevInfo, byref(deviceInterfaceData), None, 0, byref(requiredSize), byref(deviceInfoData) ) buf = create_string_buffer(requiredSize.value) pDiDetailData = cast(buf, PSP_DEVICE_INTERFACE_DETAIL_DATA) pDiDetailData.contents.cbSize = sizeof( SP_DEVICE_INTERFACE_DETAIL_DATA ) SetupDiGetDeviceInterfaceDetail( hDevInfo, byref(deviceInterfaceData), pDiDetailData, requiredSize.value, byref(requiredSize), None ) devicePath = wstring_at(addressof(pDiDetailData.contents) + 4) hardwareId = WinUsb.GetDeviceHardwareId(hDevInfo, deviceInfoData) result[hardwareId] = devicePath memberIndex += 1 return result
def GetWStringAt(self, offset, str_length=-1): """Gets a string from an offset in the buffer. Args: offset: Offset of the string from the start of the buffer. Returns: The string starting at position offset within the buffer. """ return ctypes.wstring_at(self.GetAt(offset, ctypes.sizeof(ctypes.c_wchar)), str_length)
def EnumKey(key, index): tmpbuf = ctypes.create_unicode_buffer(257) length = DWORD(257) rc = RegEnumKeyEx(key.hkey, index, ctypes.cast(tmpbuf, ctypes.c_wchar_p), ctypes.byref(length), LPDWORD(), ctypes.c_wchar_p(), LPDWORD(), ctypes.POINTER(FILETIME)()) check_code(rc) return ctypes.wstring_at(tmpbuf, length.value).rstrip(u'\x00')
def get_volume_label(self, mount_point): if not mount_point.endswith('\\'): mount_point = u"{}\\".format(mount_point) volume_name = create_unicode_buffer(MAX_PATH_NAMES) volume_name_size = DWORD(MAX_PATH_NAMES) GetVolumeInformationW(rootPathName=mount_point, volumeNameBuffer=volume_name, volumeNameSize=volume_name_size, volumeSerialNumber=None, maximumComponentLength=None, fileSystemFlags=None, fileSystemNameBuffer=None, fileSystemNameSize=DWORD(0)) return ctypes.wstring_at(ctypes.addressof(volume_name))
def EnumKey(key, index): """This calls the Windows RegEnumKeyEx function in a Unicode safe way.""" buf = ctypes.create_unicode_buffer(257) length = ctypes.wintypes.DWORD(257) rc = RegEnumKeyEx(key.handle, index, ctypes.cast(buf, ctypes.c_wchar_p), ctypes.byref(length), LPDWORD(), ctypes.c_wchar_p(), LPDWORD(), ctypes.POINTER(FileTime)()) if rc != 0: raise ctypes.WinError(2) return ctypes.wstring_at(buf, length.value).rstrip(u"\x00")