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
python类WINFUNCTYPE的实例源码
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 __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 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 __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 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 _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 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 _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 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 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 _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)