我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用ctypes.windll()。
def _copyWindows(text): GMEM_DDESHARE = 0x2000 CF_UNICODETEXT = 13 d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(0) if not isinstance(text, text_type): text = text.decode('mbcs') d.user32.OpenClipboard(0) 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()
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
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 timeval = self.get_timeval() events = [] # Add key event scan_key, key_event = self.emulate_press( vk_code, scan_code, value, timeval) events.append(scan_key) events.append(key_event) # End with a sync marker events.append(self.sync_marker(timeval)) # We are done self.write_to_pipe(events) return ctypes.windll.user32.CallNextHookEx( self.hooked, ncode, wparam, lparam)
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)
def find_lib(lib): r""" Find the DLL for a given library. Accepts a string or loaded module >>> print(find_lib('kernel32').lower()) c:\windows\system32\kernel32.dll """ if isinstance(lib, str): lib = getattr(ctypes.windll, lib) size = 1024 result = ctypes.create_unicode_buffer(size) library.GetModuleFileName(lib._handle, result, size) return result.value
def __call__(self, python_proxy, ): prototype = getattr(self.deffunc_module, self.func_name + "Prototype") params = getattr(self.deffunc_module, self.func_name + "Params") python_proxy.prototype = prototype python_proxy.params = params python_proxy.errcheck = self.error_check python_proxy.target_dll = self.APIDLL python_proxy.target_func = self.func_name params_name = [param[1] for param in params] if (self.error_check.__doc__): doc = python_proxy.__doc__ doc = doc if doc else "" python_proxy.__doc__ = doc + "\nErrcheck:\n " + self.error_check.__doc__ def generate_ctypes_function(): try: c_prototyped = prototype((self.func_name, getattr(ctypes.windll, self.APIDLL)), params) except (AttributeError, WindowsError): raise ExportNotFound(self.func_name, self.APIDLL) c_prototyped.errcheck = self.error_check self._cprototyped = c_prototyped def perform_call(*args): if len(params_name) != len(args): print("ERROR:") print("Expected params: {0}".format(params_name)) print("Just Got params: {0}".format(args)) raise ValueError("I do not have all parameters: how is that possible ?") for param_name, param_value in zip(params_name, args): if param_value is NeededParameter: raise TypeError("{0}: Missing Mandatory parameter <{1}>".format(self.func_name, param_name)) if self._cprototyped is None: generate_ctypes_function() return self._cprototyped(*args) setattr(python_proxy, "ctypes_function", perform_call) setattr(python_proxy, "force_resolution", generate_ctypes_function) return python_proxy
def force_resolution(self): try: c_prototyped = self.prototype((self.target_func, getattr(ctypes.windll, self.target_dll)), self.params) except AttributeError: raise ExportNotFound(self.target_func, self.target_dll) c_prototyped.errcheck = functools.wraps(self.error_check)(functools.partial(self.error_check, self.target_func)) self._ctypes_function = c_prototyped
def enable_library_ordinals(library_num): idaname = "ida64" if Const.EA64 else "ida" if sys.platform == "win32": dll = ctypes.windll[idaname + ".wll"] elif sys.platform == "linux2": dll = ctypes.cdll["lib" + idaname + ".so"] elif sys.platform == "darwin": dll = ctypes.cdll["lib" + idaname + ".dylib"] else: print "[ERROR] Failed to enable ordinals" return idati = ctypes.POINTER(TypeLibrary.til_t).in_dll(dll, "idati") dll.enable_numbered_types(idati.contents.base[library_num], True)
def not_windows(): raise SystemError( "Invalid platform. ctypes.windll must be available." )
def __init__(self, dllname, funcname): self.__dllname = dllname self.__funcname = funcname self.__func = getattr(getattr(ctypes.windll, dllname), funcname)
def _pasteWindows(): CF_UNICODETEXT = 13 d = ctypes.windll d.user32.OpenClipboard(0) handle = d.user32.GetClipboardData(CF_UNICODETEXT) data = ctypes.c_wchar_p(handle).value d.user32.CloseClipboard() return data
def setUp(self): self.mox = mox.Mox() ctypes.windll = self.mox.CreateMockAnything() ctypes.windll.kernel32 = self.mox.CreateMockAnything() ctypes.windll.kernel32.CreateFileW = self.mox.CreateMockAnything() ctypes.windll.kernel32.ReadDirectoryChangesW = self.mox.CreateMockAnything() ctypes.windll.kernel32.CancelIoEx = self.mox.CreateMockAnything() ctypes.windll.kernel32.CloseHandle = self.mox.CreateMockAnything() ctypes.WinError = WinError
def test_with_no_change(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(31415) # pylint: disable=unused-argument def found_nothing( handle, buff, size, recursive, change_type, size_returned_by_ref, unused1, unused2): ctypes.cast(size_returned_by_ref, ctypes.POINTER(ctypes.c_ulong))[0] = 0L ctypes.windll.kernel32.ReadDirectoryChangesW( 31415, mox.IgnoreArg(), mox_c(4096), True, mox_c(351), mox.IgnoreArg(), None, None).WithSideEffects(found_nothing).AndReturn(-1) ctypes.windll.kernel32.CancelIoEx(31415, None) ctypes.windll.kernel32.CloseHandle(31415) self.mox.ReplayAll() watcher.start() watcher.quit() self.assertEqual(watcher.changes(), set()) self.mox.VerifyAll()
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()
def listen(): """Listen for keyboard input.""" msg = MSG() ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
def install_handle_input(self): """Install the hook.""" self.pointer = self.get_fptr() self.hooked = ctypes.windll.user32.SetWindowsHookExA( 13, self.pointer, ctypes.windll.kernel32.GetModuleHandleW(None), 0 ) if not self.hooked: return False return True
def uninstall_handle_input(self): """Remove the hook.""" if self.hooked is None: return ctypes.windll.user32.UnhookWindowsHookEx(self.hooked) self.hooked = None
def listen(): """Listen for mouse input.""" msg = MSG() ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
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 break else: # We didn't find an xinput library warn("No xinput driver dll found, gamepads not supported.")
def install_handle_input(self): """Install the hook.""" self.pointer = self.get_fptr() self.hooked = ctypes.windll.user32.SetWindowsHookExA( 14, self.pointer, ctypes.windll.kernel32.GetModuleHandleW(None), 0 ) if not self.hooked: return False return True
def platform_specific_functions(): # use stddecl on windows, cdecl on all other platforms d = {'library_loader' : ctypes.cdll ,'function_pointer' : ctypes.CFUNCTYPE } if platform.system() in ('Windows', 'Microsoft'): d['library_loader'] = ctypes.windll d['function_pointer'] = ctypes.WINFUNCTYPE return d
def jvm_load(prefer=None): """ Loads the JVM dynamic library. The `prefer` argument works like for `jvm_find`. If the library is already loaded, this produces a warning if `prefer` doesn't match the loaded library, otherwise it does nothing. """ global libjvm, libjvm_type if libjvm is not None: if prefer is not None and prefer != libjvm_type: import warnings warnings.warn('Already loaded JVM "%s", so preferred JVM "%s" is unloadable'%(libjvm_type,prefer)) return jvm,libjvm_type = jvm_find(prefer) libjvm = (ctypes.windll if is_win else ctypes.cdll).LoadLibrary(jvm)
def quick_win_define(name, output, *args, **kwargs): dllname, fname = name.split('.') params = kwargs.get('params', None) if params: params = tuple([(x, ) for x in params]) func = (WINFUNCTYPE(output, *args))((fname, getattr(windll, dllname)), params) err = kwargs.get('err', err_on_zero_or_null_check) if err: func.errcheck = err return func
def __init__(self, window_name, with_alpha=False, bbox=None): window = windll.user32.FindWindowW(None, window_name) self.window = window rect = GetClientRect(window) self.width = rect.right - rect.left self.height = rect.bottom - rect.top if bbox: bbox = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]] if not bbox[2] or not bbox[3]: bbox[2] = self.width - bbox[0] bbox[3] = self.height - bbox[1] self.x, self.y, self.width, self.height = bbox else: self.x = 0 self.y = 0 self.windowDC = GetDC(window) self.memoryDC = CreateCompatibleDC(self.windowDC) self.bitmap = CreateCompatibleBitmap(self.windowDC, self.width, self.height) self.bitmapInfo = BITMAPINFOHEADER() self.bitmapInfo.biSize = sizeof(BITMAPINFOHEADER) self.bitmapInfo.biPlanes = 1 self.bitmapInfo.biBitCount = 32 if with_alpha else 24 self.bitmapInfo.biWidth = self.width self.bitmapInfo.biHeight = -self.height self.bitmapInfo.biCompression = BI_RGB self.bitmapInfo.biSizeImage = 0 self.channels = 4 if with_alpha else 3 self.closed = False
def test_with_change(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(31415) # pylint: disable=unused-argument def found_something( handle, buff, size, recursive, change_type, size_returned_by_ref, unused1, unused2): parray = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # next offset = 0 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # Action 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # 4 * 10 chrs 0x74, 0x00, 0x00, 0x00, # 't' 0x65, 0x00, 0x00, 0x00, # 'e' 0x73, 0x00, 0x00, 0x00, # 's' 0x74, 0x00, 0x00, 0x00, # 't' 0x20, 0x00, 0x00, 0x00, # ' ' 0x73, 0x00, 0x00, 0x00, # 's' 0x74, 0x00, 0x00, 0x00, # 't' 0x75, 0x00, 0x00, 0x00, # 'u' 0x66, 0x00, 0x00, 0x00, # 'f' 0x66, 0x00, 0x00, 0x00] # 'f' nbuff = (ctypes.c_ubyte * len(parray))(*parray) ctypes.memmove( buff, ctypes.addressof(nbuff), ctypes.sizeof(nbuff)) psize = ctypes.cast(size_returned_by_ref, ctypes.POINTER(ctypes.c_ulong)) psize[0] = ctypes.sizeof(nbuff) ctypes.windll.kernel32.ReadDirectoryChangesW( 31415, mox.IgnoreArg(), mox_c(win32_file_watcher._BUFF_SIZE), True, mox_c(351), mox.IgnoreArg(), None, None).WithSideEffects(found_something).AndReturn(1) ctypes.windll.kernel32.CancelIoEx(31415, None) ctypes.windll.kernel32.CloseHandle(31415) self.mox.ReplayAll() watcher.start() watcher.quit() self.assertEqual(watcher.changes(), {'test stuff'}) self.mox.VerifyAll()
def _count_devices(self): """See what Windows' GetRawInputDeviceList wants to tell us. For now, we are just seeing if there is at least one keyboard and/or mouse attached. GetRawInputDeviceList could be used to help distinguish between different keyboards and mice on the system in the way Linux can. However, Roma uno die non est condita. """ number_of_devices = ctypes.c_uint() if ctypes.windll.user32.GetRawInputDeviceList( ctypes.POINTER(ctypes.c_int)(), ctypes.byref(number_of_devices), ctypes.sizeof(RawInputDeviceList)) == -1: warn("Call to GetRawInputDeviceList was unsuccessful." "We have no idea if a mouse or keyboard is attached.", RuntimeWarning) return devices_found = (RawInputDeviceList * number_of_devices.value)() if ctypes.windll.user32.GetRawInputDeviceList( devices_found, ctypes.byref(number_of_devices), ctypes.sizeof(RawInputDeviceList)) == -1: warn("Call to GetRawInputDeviceList was unsuccessful." "We have no idea if a mouse or keyboard is attached.", RuntimeWarning) return for device in devices_found: if device.dwType == 0: self._raw_device_counts['mice'] += 1 elif device.dwType == 1: self._raw_device_counts['keyboards'] += 1 elif device.dwType == 2: self._raw_device_counts['otherhid'] += 1 else: self._raw_device_counts['unknown'] += 1