我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.WINFUNCTYPE。
def window__get_thread_window_handles(thread_process_id): """ :param thread_process_id: thread process ID, as from window__get_thread_process_id :return: hwnd for all top-level windows with this thread process id. """ ret = [] def callback(hwnd, lparam): ret.append(hwnd) return True enum_win_proc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int)) windll.user32.EnumThreadWindows(wintypes.DWORD(thread_process_id), enum_win_proc(callback), None) return ret
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
def _set_argtypes(self): ''' Functions arguments. ''' self.MONITORENUMPROC = WINFUNCTYPE(INT, DWORD, DWORD, POINTER(RECT), DOUBLE) windll.user32.GetSystemMetrics.argtypes = [INT] windll.user32.EnumDisplayMonitors.argtypes = [HDC, c_void_p, self.MONITORENUMPROC, LPARAM] windll.user32.GetWindowDC.argtypes = [HWND] windll.gdi32.CreateCompatibleDC.argtypes = [HDC] windll.gdi32.CreateCompatibleBitmap.argtypes = [HDC, INT, INT] windll.gdi32.SelectObject.argtypes = [HDC, HGDIOBJ] windll.gdi32.BitBlt.argtypes = [HDC, INT, INT, INT, INT, HDC, INT, INT, DWORD] windll.gdi32.DeleteObject.argtypes = [HGDIOBJ] windll.gdi32.GetDIBits.argtypes = [HDC, HBITMAP, UINT, UINT, c_void_p, POINTER(BITMAPINFO), UINT]
def detectForgroundWindows(): #Stolen fom https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/ EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible titles = [] def foreach_window(hwnd, lParam): if IsWindowVisible(hwnd): length = GetWindowTextLength(hwnd) buff = ctypes.create_unicode_buffer(length + 1) GetWindowText(hwnd, buff, length + 1) titles.append(buff.value) return True EnumWindows(EnumWindowsProc(foreach_window), 0) return titles
def WINFUNCTYPE(restype, *argtypes, **kw): flags = _FUNCFLAG_STDCALL if kw.pop("use_errno", False): flags |= ctypes._FUNCFLAG_USE_ERRNO if kw.pop("use_last_error", False): flags |= ctypes._FUNCFLAG_USE_LASTERROR if kw: raise ValueError("unexpected keyword argument(s) %s" % kw.keys()) try: return ctypes._win_functype_cache[(restype, argtypes, flags)] except KeyError: class WinFunctionType(ctypes._CFuncPtr): _argtypes_ = argtypes _restype_ = restype _flags_ = flags ctypes._win_functype_cache[(restype, argtypes, flags)] = WinFunctionType return WinFunctionType
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())))
def revealWindows(): print '[*] Getting window titles' EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible titles = [] def foreach_window(hwnd, lParam): if IsWindowVisible(hwnd): length = GetWindowTextLength(hwnd) buff = ctypes.create_unicode_buffer(length + 1) GetWindowText(hwnd, buff, length + 1) titles.append(buff.value) return True EnumWindows(EnumWindowsProc(foreach_window), 0) return titles # windows = revealWindows() # for title in windows: # print title
def finder(): """ ????????????????? """ team = set() buff = ctypes.create_unicode_buffer(32) @ctypes.WINFUNCTYPE(ctypes.wintypes.BOOL, ctypes.wintypes.HWND, ctypes.wintypes.LPARAM) def check(hwnd, extra): if op.IsWindowVisible(hwnd): op.GetWindowTextW(hwnd, buff, 32) if '????' in buff.value: team.add(hwnd) return 1 op.EnumWindows(check, 0) return {unity(main) for main in team if team}
def finder(register): ''' ???????broker??????? ''' team = set() buff = buffer(32) @ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM) def check(hwnd, extra): if op.IsWindowVisible(hwnd): op.GetWindowTextW(hwnd, buff, 32) if '????' in buff.value: team.add(hwnd) return 1 op.EnumWindows(check, 0) def get_nickname(hwnd): account = hwnd for i in 59392, 0, 1711: account = op.GetDlgItem(account, i) op.SendMessageW(account, WM_GETTEXT, 32, buff) return register.get(buff.value[-3:]) return {get_nickname(hwnd): unity(hwnd) for hwnd in team if hwnd}
def list_alttab_windows(cls): """ Return the list of the windows handles that are currently guessed to be eligible to the Alt+Tab panel. Raises a OSError exception on error. """ # LPARAM is defined as LONG_PTR (signed type) if ctypes.sizeof(ctypes.c_long) == ctypes.sizeof(ctypes.c_void_p): LPARAM = ctypes.c_long elif ctypes.sizeof(ctypes.c_longlong) == ctypes.sizeof(ctypes.c_void_p): LPARAM = ctypes.c_longlong EnumWindowsProc = ctypes.WINFUNCTYPE( ctypes.c_bool, ctypes.c_void_p, LPARAM) def _enum_proc(hwnd, lparam): try: if cls.is_alttab_window(hwnd): handles.append(hwnd) except OSError: pass return True handles = [] ctypes.windll.user32.EnumWindows(EnumWindowsProc(_enum_proc), 0) return handles
def window__enum_window_handles(callback): # noinspection PyUnusedLocal def callback_wrapper(hwnd, lparam): return callback(hwnd) enum_win_proc = WINFUNCTYPE(c_bool, c_int, POINTER(c_int)) windll.user32.EnumWindows(enum_win_proc(callback_wrapper), None)
def window__get_child_window_handles(hwnd_parent): ret = [] def callback(hwnd, lparam): ret.append(hwnd) return True enum_win_proc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int)) windll.user32.EnumChildWindows(hwnd_parent, enum_win_proc(callback), None) return ret
def monitor__find_monitors(): ret = [] def callback(h_monitor, hdc_monitor, lprc_monitor, lParam): # hMonitor: display monitor handle # hdcMonitor: device context handle; color attributes + clipping region # lprcMonitor: RECT structure w/ device-context coordinates. ret.append({ 'monitor_handle': h_monitor, 'device_context_handle': hdc_monitor, 'left': lprc_monitor.contents.left, 'right': lprc_monitor.contents.right, 'top': lprc_monitor.contents.top, 'bottom': lprc_monitor.contents.bottom, 'width': lprc_monitor.contents.right - lprc_monitor.contents.left, 'height': lprc_monitor.contents.bottom - lprc_monitor.contents.top, 'primary': len(ret) == 0, 'index': len(ret), }) return True enum_monitor_proc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int), POINTER(wintypes.RECT), POINTER(c_int)) if EnumDisplayMonitors(None, None, enum_monitor_proc(callback), None) == 0: raise Exception("Could not find monitors") # for i in ret: # info = POINTER(wintypes.MONITORINFOEX()) # if GetMonitorInfo(i['monitor_handle'], info) != 0: # i['primary'] = info.contents.dwFlags == MONITORINFOF_PRIMARY # i['name'] = str(info.contents.szDevice) return ret
def _get_calling_conv(*args): if sys.platform == 'win32': return ctypes.WINFUNCTYPE(*args) else: return ctypes.CFUNCTYPE(*args)
def __init__(self, IAT_entry, callback, types=None): if types is None: if not hasattr(callback, "_types_info"): raise ValueError("Callback for IATHook has no type infomations") types = callback._types_info self.original_types = types self.callback_types = self.transform_arguments(self.original_types) self.entry = IAT_entry self.callback = callback self.stub = ctypes.WINFUNCTYPE(*self.callback_types)(self.hook_callback) self.stub_addr = ctypes.cast(self.stub, PVOID).value self.realfunction = ctypes.WINFUNCTYPE(*types)(IAT_entry.nonhookvalue) self.is_enable = False #IATHook.yolo.append(self)
def is_wow_64(hProcess): try: fnIsWow64Process = get_func_addr("kernel32.dll", "IsWow64Process") except winproxy.Kernel32Error: return False IsWow64Process = ctypes.WINFUNCTYPE(BOOL, HANDLE, ctypes.POINTER(BOOL))(fnIsWow64Process) Wow64Process = BOOL() res = IsWow64Process(hProcess, ctypes.byref(Wow64Process)) if res: return bool(Wow64Process) raise ctypes.WinError()
def _create_vtable(self, interface): implems = [] names = [] for index, name, method in self.extract_methods_order(interface): func_implem = getattr(self, name) #PVOID is 'this' types = [method.restype, PVOID] + list(method.argtypes) implems.append(ctypes.WINFUNCTYPE(*types)(func_implem)) names.append(name) class Vtable(ctypes.Structure): _fields_ = [(name, ctypes.c_void_p) for name in names] return Vtable(*[ctypes.cast(x, ctypes.c_void_p) for x in implems]), implems
def _enumerate_windows(self, visible=True): ''' Loops through the titles of all the "windows." Spits out too much junk to to be of immediate use. Keeping it here to remind me how the ctypes callbacks work. ''' # raise NotImplementedError('Not ready yet. Git outta here!') titles = [] handlers = [] def worker(hwnd, lParam): length = user32.GetWindowTextLengthW(hwnd) + 1 b = ctypes.create_unicode_buffer(length) user32.GetWindowTextW(hwnd, b, length) if visible and user32.IsWindowVisible(hwnd): title = b.value if title: titles.append(title) handlers.append(hwnd) return True WNDENUMPROC = ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM) if not user32.EnumWindows(WNDENUMPROC(worker), True): raise ctypes.WinError() else: return handlers, titles
def __init__(self): # Initialize freeimage lib as None self._lib = None # A lock to create thread-safety self._lock = threading.RLock() # Init log messages lists self._messages = [] # Select functype for error handler if sys.platform.startswith('win'): functype = ctypes.WINFUNCTYPE else: functype = ctypes.CFUNCTYPE # Create output message handler @functype(None, ctypes.c_int, ctypes.c_char_p) def error_handler(fif, message): message = message.decode('utf-8') self._messages.append(message) while (len(self._messages)) > 256: self._messages.pop(0) # Make sure to keep a ref to function self._error_handler = error_handler
def allow_interruption(*callbacks): if sys.platform == 'win32': from ctypes import WINFUNCTYPE, windll from ctypes.wintypes import BOOL, DWORD kernel32 = windll.LoadLibrary('kernel32') phandler_routine = WINFUNCTYPE(BOOL, DWORD) setconsolectrlhandler = kernel32.SetConsoleCtrlHandler setconsolectrlhandler.argtypes = (phandler_routine, BOOL) setconsolectrlhandler.restype = BOOL @phandler_routine def shutdown(event): if event == 0: for loop, cb in callbacks: loop.call_soon_threadsafe(cb) return 1 return 0 if setconsolectrlhandler(shutdown, 1) == 0: raise WindowsError() else: def handler(*args): for loop, cb in callbacks: loop.call_soon_threadsafe(cb) signal.signal(signal.SIGINT, handler) try: yield finally: if sys.platform == 'win32': if setconsolectrlhandler(shutdown, 0) == 0: raise WindowsError() else: signal.signal(signal.SIGINT, signal.SIG_DFL)
def get_field(self): return ctypes.WINFUNCTYPE(self.restype, *self.argtypes)
def link_GL(name, restype, argtypes, requires=None, suggestions=None): try: func = getattr(gl_lib, name) func.restype = restype func.argtypes = argtypes decorate_function(func, name) return func except AttributeError: # Not in opengl32.dll. Try and get a pointer from WGL. try: fargs = (restype,) + tuple(argtypes) ftype = ctypes.WINFUNCTYPE(*fargs) if _have_get_proc_address: from pyglet.gl import gl_info if gl_info.have_context(): address = wglGetProcAddress(name) if address: func = cast(address, ftype) decorate_function(func, name) return func else: # Insert proxy until we have a context return WGLFunctionProxy(name, ftype, requires, suggestions) except: pass return missing_function(name, requires, suggestions)
def link_GLU(name, restype, argtypes, requires=None, suggestions=None): try: func = getattr(glu_lib, name) func.restype = restype func.argtypes = argtypes decorate_function(func, name) return func except AttributeError: # Not in glu32.dll. Try and get a pointer from WGL. try: fargs = (restype,) + tuple(argtypes) ftype = ctypes.WINFUNCTYPE(*fargs) if _have_get_proc_address: from pyglet.gl import gl_info if gl_info.have_context(): address = wglGetProcAddress(name) if address: func = cast(address, ftype) decorate_function(func, name) return func else: # Insert proxy until we have a context return WGLFunctionProxy(name, ftype, requires, suggestions) except: pass return missing_function(name, requires, suggestions)
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)
def find(keyword): """ ??????????? """ @ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p) def check(hwnd, keyword): """ ?? """ if api.IsWindowVisible(hwnd)\ and api.GetWindowTextW(hwnd, buff, 32) > 6 and keyword in buff.value: team.add(hwnd) return 1 for i in range(10): api.EnumWindows(check, keyword) time.sleep(3) if team: break return {Puppet(main) for main in team}
def find(keyword): """ ??????????? """ @ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p) def check(hwnd, keyword): """ ?? """ if api.IsWindowVisible(hwnd)\ and api.GetWindowTextW(hwnd, buff, 32) > 6 and keyword in buff.value: team.add(hwnd) return 1 api.EnumWindows(check, keyword) return {Puppet(main) for main in team}
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 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 get_display_monitors(self): ''' Enumerates and returns a list of virtual screen coordinates for the attached display devices output = [ (left, top, right, bottom), # Monitor 1 (left, top, right, bottom) # Monitor 2 # etc... ] ''' display_coordinates = [] def _monitorEnumProc(hMonitor, hdcMonitor, lprcMonitor, dwData): # print('call result:', hMonitor, hdcMonitor, lprcMonitor, dwData) # print('DC:', user32.GetWindowDC(hMonitor)) coordinates = ( lprcMonitor.contents.left, lprcMonitor.contents.top, lprcMonitor.contents.right, lprcMonitor.contents.bottom ) display_coordinates.append(coordinates) return True # Callback Factory MonitorEnumProc = WINFUNCTYPE( ctypes.c_bool, ctypes.wintypes.HMONITOR, ctypes.wintypes.HDC, ctypes.POINTER(RECT), ctypes.wintypes.LPARAM ) # Make the callback function enum_callback = MonitorEnumProc(_monitorEnumProc) # Enumerate the windows user32.EnumDisplayMonitors( None, None, enum_callback, 0 ) return display_coordinates
def __init__(self): # Initialize freeimage lib as None self._lib = None # A lock to create thread-safety self._lock = threading.RLock() # Init log messages lists self._messages = [] # Select functype for error handler if sys.platform.startswith('win'): functype = ctypes.WINFUNCTYPE else: functype = ctypes.CFUNCTYPE # Create output message handler @functype(None, ctypes.c_int, ctypes.c_char_p) def error_handler(fif, message): message = message.decode('utf-8') self._messages.append(message) while (len(self._messages)) > 256: self._messages.pop(0) # Make sure to keep a ref to function self._error_handler = error_handler # Load library and register API success = False try: # Try without forcing a download, but giving preference # to the imageio-provided lib (if previously downloaded) self._load_freeimage() self._register_api() if self._lib.FreeImage_GetVersion().decode('utf-8') >= '3.15': success = True except OSError: pass if not success: # Ensure we have our own lib, try again get_freeimage_lib() self._load_freeimage() self._register_api() # Wrap up self._lib.FreeImage_SetOutputMessage(self._error_handler) self._lib_version = self._lib.FreeImage_GetVersion().decode('utf-8')
def fix_win_sys_argv(encoding): """Converts sys.argv to 'encoding' encoded string. utf-8 is recommended. Works around <http://bugs.python.org/issue2128>. """ global _SYS_ARGV_PROCESSED if _SYS_ARGV_PROCESSED: return False # These types are available on linux but not Mac. # pylint: disable=no-name-in-module,F0401 from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import LPCWSTR, LPWSTR # <http://msdn.microsoft.com/en-us/library/ms683156.aspx> GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32)) # <http://msdn.microsoft.com/en-us/library/bb776391.aspx> CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( ('CommandLineToArgvW', windll.shell32)) argc = c_int(0) argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc)) argv = [ argv_unicode[i].encode(encoding, 'replace') for i in xrange(0, argc.value)] if not hasattr(sys, 'frozen'): # If this is an executable produced by py2exe or bbfreeze, then it # will have been invoked directly. Otherwise, unicode_argv[0] is the # Python interpreter, so skip that. argv = argv[1:] # Also skip option arguments to the Python interpreter. while len(argv) > 0: arg = argv[0] if not arg.startswith(u'-') or arg == u'-': break argv = argv[1:] if arg == u'-m': # sys.argv[0] should really be the absolute path of the # module source, but never mind. break if arg == u'-c': argv[0] = u'-c' break sys.argv = argv _SYS_ARGV_PROCESSED = True return True
def __init__(self): from ctypes import WINFUNCTYPE, windll from ctypes.wintypes import BOOL, HANDLE, DWORD, WORD self.__original_stderr = sys.stderr self.__stdout = None self.__SetConsoleTextAttribute = None # Work around <http://bugs.python.org/issue6058>. # codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) # Make Unicode console output work independently of the current code page. # This also fixes <http://bugs.python.org/issue1602>. # Credit to Michael Kaplan <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx> # and TZOmegaTZIOY # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>. try: # <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx> # HANDLE WINAPI GetStdHandle(DWORD nStdHandle); # returns INVALID_HANDLE_VALUE, NULL, or a valid handle # # <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx> # DWORD WINAPI GetFileType(DWORD hFile); # # <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx> # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode); STD_OUTPUT_HANDLE = DWORD(-11) INVALID_HANDLE_VALUE = DWORD(-1).value GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32)) self.__SetConsoleTextAttribute = WINFUNCTYPE(BOOL, HANDLE, WORD)(("SetConsoleTextAttribute", windll.kernel32)) self.__stdout = GetStdHandle(STD_OUTPUT_HANDLE) if self.__stdout == INVALID_HANDLE_VALUE: self.__stdout = None except Exception as e: self.__stdout = None self._complain("exception %r while fixing up sys.stdout and sys.stderr\n" % (str(e),)) # If any exception occurs in this code, we'll probably try to print it on stderr, # which makes for frustrating debugging if stderr is directed to our wrapper. # So be paranoid about catching errors and reporting them to original_stderr, # so that we can at least see them.