【问题标题】:Keypress event to an unfocused window - Win32api未聚焦窗口的按键事件 - Win32api
【发布时间】:2018-08-13 15:38:35
【问题描述】:

我想编写一个模拟按键按下和释放的脚本,以便输入进入特定窗口,即使它不是焦点窗口并且在后台或最小化。我想知道这是否可能。

当焦点窗口(输入所在的位置)是我决定的窗口时,我制作的脚本每 2 秒执行一次,否则什么也不会发生,然后它会再次循环。但这不是我的目标。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import win32api, win32gui, win32con
import time

def press():
    win32api.keybd_event(0x08, 0,0,0) # 0x08 is the hex for the return key
    time.sleep(.1)
    win32api.keybd_event(0x08,0 ,win32con.KEYEVENTF_KEYUP ,0)

def __get_window():
    CurrentWindow = win32gui.GetWindowText(win32gui.GetForegroundWindow())
    return CurrentWindow

if __name__ == "__main__":      

    while True:

        if __get_window() == "PROCESS_NAME": # Name of the process
            press()

        time.sleep(2)

感谢您的帮助。

【问题讨论】:

    标签: python python-2.7 automation bots win32gui


    【解决方案1】:
     this solution is for c++ but i think method's name should be same as defined in 
     win32api python 
    
     consider hwnd as window handle
     and Vk_A as value of key which you want to remotely pressed and released
     you need to use "SendMessage" or "PostMessage" method
    
     if you know window handle you can use 
       SendMessage(hwnd, WM_SETFOCUS, 0, 0) 
     or
       SendMessage(hwnd, WM_ACTIVATE, WA_ACTIVE, 0)
    
     then you need to use following methods together
       SendMessage(hwnd, WM_KEYDOWN, Vk_A, 0)
       SendMessage(hwnd, WM_KEYUP, Vk_A, 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2011-06-05
      • 1970-01-01
      相关资源
      最近更新 更多