コード例 #1
0
def press_keys(collection_of_keys,
               delay_between_presses=0.05,
               delay_between_releases=0.05):
    """
    Presses and then releases key for each key in collection.
    Ex: press_keys(["shift"]) will have shift key pressed, not type out shift.
    Ex: press_keys(["H","e","l","l","o")  to have Hello typed. Should use type_out_string if want to type out words.
    :param collection_of_keys: A collection of strings which are names of keyboard keys.
    :param delay_between_presses: Time to wait before press a key when about to press a key.
    :param delay_between_releases: Time to wait before releasing a key when about to release it.
    """
    for key in collection_of_keys:
        vkcode, needshift = identify_correct_key(key)
        if needshift:
            sleep(delay_between_presses)
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0), 0, 0)
        sleep(delay_between_presses)
        win32api.keybd_event(vkcode, win32api.MapVirtualKey(vkcode, 0), 0, 0)
        sleep(delay_between_releases)
        win32api.keybd_event(vkcode, win32api.MapVirtualKey(vkcode, 0),
                             win32con.KEYEVENTF_KEYUP, 0)
        if needshift:
            sleep(delay_between_releases)
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0),
                win32con.KEYEVENTF_KEYUP, 0)
コード例 #2
0
ファイル: sound.py プロジェクト: mrKallah/Virtual-Assistant
def control_music_win(command, obj_manager):
    return_value = False
    # if the music should be toggled then emulate a play music keyboard press.
    for trigger in next_song_triggers:
        if trigger in command:
            return_value = True
            if "stop" in command:
                tts("stopping music", obj_manager)
            elif "pause" in command:
                tts("pausing music", obj_manager)
            else:
                tts("playing music", obj_manager)

            vk_media_play_pause = 0xB3
            hardware_code = win32api.MapVirtualKey(vk_media_play_pause, 0)
            win32api.keybd_event(vk_media_play_pause, hardware_code)

    # if next song is in string then emulate a skip key keyboard press
    for trigger in skip_song_trigger:
        if trigger in command:
            return_value = True
            tts("skipping current song", obj_manager)
            vk_media_next_track = 0xB0
            hardware_code = win32api.MapVirtualKey(vk_media_next_track, 0)
            win32api.keybd_event(vk_media_next_track, hardware_code)

    return return_value
コード例 #3
0
def press_keys_and_hold(collection_of_keys,
                        delay_between_presses=0.05,
                        delay_between_shift_release=0.05):
    """
    Presses and holds key down for all keys in collection.
    Keeping key pressed won't cause key to be invoked several times (i.e. won't get several a's by holding a key down.)
    Does press and release shift key, if the key specified requires shift state.
    :param collection_of_keys: A collection of strings which are names of keyboard keys.
    :param delay_between_presses: Time to wait before press a key when about to press a key.
    :param delay_between_shift_release: Time to wait before releasing the shift key when about to release it.
    """
    for key in collection_of_keys:
        vkcode, needshift = identify_correct_key(key)
        if needshift:
            sleep(delay_between_presses)
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0), 0, 0)
        sleep(delay_between_presses)
        win32api.keybd_event(vkcode, win32api.MapVirtualKey(vkcode, 0), 0, 0)
        if needshift:
            sleep(delay_between_shift_release)
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0),
                win32con.KEYEVENTF_KEYUP, 0)
コード例 #4
0
ファイル: coc_customer.py プロジェクト: liuxingmoon/tool
def open_windows(coc_clan_dict):  #打开QQ和wechat会话窗口,发送消息
    try:
        qq_hwnd = win32gui.FindWindow(None, 'QQ')
        wechat_hwnd = win32gui.FindWindow(None, '微信')
        print("捕捉到QQ主窗体的句柄为:" + str(qq_hwnd))
        print("捕捉到微信主窗体的句柄为:" + str(wechat_hwnd))
        win32gui.ShowWindow(qq_hwnd, win32con.SW_SHOW)
        #win32gui.ShowWindow(wechat_hwnd,win32con.SW_SHOW)
        print("正在打开会话窗口...\n")
        time.sleep(1)
        for coc_clan_name in coc_clan_dict:
            #打开会话窗口
            setText(coc_clan_name)
            win32api.keybd_event(13, 0, 0, 0)
            win32gui.SetForegroundWindow(qq_hwnd)
            win32gui.SetActiveWindow(qq_hwnd)
            time.sleep(1)
            win32gui.SendMessage(qq_hwnd, 770, 0, 0)
            time.sleep(1)
            win32gui.SetForegroundWindow(qq_hwnd)
            win32gui.SetActiveWindow(qq_hwnd)
            win32api.keybd_event(0x0D, win32api.MapVirtualKey(0x0D, 0), 0, 0)
            win32api.keybd_event(0x0D, win32api.MapVirtualKey(0x0D, 0),
                                 win32con.KEYEVENTF_KEYUP, 0)
            #发送信息
            send_qq(coc_clan_dict[coc_clan_name])
    except:
        print("没有找到QQ或微信程序")
コード例 #5
0
def type_out_string(string: str,
                    delay_between_presses=0.05,
                    delay_between_releases=0.05):
    """
    Invokes key events to type out word as if were typing it out on a physical keyboard.
    Ex: type_out_string("shift") would have the word shift typed out, not press the shift key.
    :param string: Word or sentence want typed out.
    :param delay_between_presses: Time to wait before press a key when about to press a key.
    :param delay_between_releases: Time to wait before releasing a key when about to release it.
    """
    for character in string:
        vkcode, needshift = identify_correct_key(character)
        if needshift:
            sleep(delay_between_presses)
            # http://timgolden.me.uk/pywin32-docs/win32api__keybd_event_meth.html
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0), 0, 0)
        sleep(delay_between_presses)
        win32api.keybd_event(vkcode, win32api.MapVirtualKey(vkcode, 0), 0, 0)
        sleep(delay_between_releases)
        win32api.keybd_event(vkcode, win32api.MapVirtualKey(vkcode, 0),
                             win32con.KEYEVENTF_KEYUP, 0)
        if needshift:
            sleep(delay_between_releases)
            win32api.keybd_event(
                VK_CODE['left_shift'],
                win32api.MapVirtualKey(VK_CODE['left_shift'], 0),
                win32con.KEYEVENTF_KEYUP, 0)
コード例 #6
0
 def passkey_event(self, mykey, t=1):  #键码输入
     win32api.keybd_event(self.VK_CODE[mykey],
                          win32api.MapVirtualKey(self.VK_CODE[mykey], 0), 0,
                          0)
     time.sleep(0.1)
     win32api.keybd_event(self.VK_CODE[mykey],
                          win32api.MapVirtualKey(self.VK_CODE[mykey], 0),
                          win32con.KEYEVENTF_KEYUP, 0)
コード例 #7
0
def pressStr(key):

    for letter in key:
        letter = vk_keys(letter)
        win32api.keybd_event(letter,win32api.MapVirtualKey(letter,0),0,0) #释放按键
        sleep(np.abs((rand()-0.5)/10)+0.2)
        win32api.keybd_event(letter,win32api.MapVirtualKey(letter,0),2,0)  #v键位码是86

    sleep(np.abs((rand()-0.5)/10)+0.2)
コード例 #8
0
def CtrlS():
    win32api.keybd_event(17, win32api.MapVirtualKey(17, 0), 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(83, win32api.MapVirtualKey(83, 0), 0, 0)
    time.sleep(0.2)
    win32api.keybd_event(83, win32api.MapVirtualKey(83, 0),
                         win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(0.1)
    win32api.keybd_event(17, win32api.MapVirtualKey(17, 0),
                         win32con.KEYEVENTF_KEYUP, 0)
コード例 #9
0
ファイル: capture.py プロジェクト: wau/Thermal2
def send_key(key):
    # send key down event
    key = char2key(key)
    time.sleep(.04)
    win32api.keybd_event(key, win32api.MapVirtualKey(key, 0), 0, 0)
    # wait for it to get registered.
    # You might need to increase this time for some applications
    time.sleep(.04)
    # send key up event
    win32api.keybd_event(key, win32api.MapVirtualKey(key, 0),
                         win32con.KEYEVENTF_KEYUP, 0)
コード例 #10
0
def getSC(userinput):
    if userinput.isupper():
        # Convert input to Virtual Key
        key = getVK(userinput.lower())

        # Convert Virtual Key to Scan Code
        scancode = win32api.MapVirtualKey(key, 0)
        return scancode

    else:
        key = getVK(userinput)
        scancode = win32api.MapVirtualKey(key, 0)
        return scancode
コード例 #11
0
ファイル: key_event.py プロジェクト: akalinn/game_demo
def pressKey(key):
    '''
    keybd_event:
    1. virtual key
    2. key scancode
    3. dwflag 0 is press and 2 is release
    4. dwextrainfo
    '''
    key = vk_keys(key)
    win32api.keybd_event(key, win32api.MapVirtualKey(key, 0), 0, 0)  #释放按键
    sleep(np.abs((rand() - 0.5) / 10) + 0.2)
    win32api.keybd_event(key, win32api.MapVirtualKey(key, 0), 2, 0)  #v键位码是86
    #win32api.PostMessage(hwnd,win32con.WM_KEYDOWN,65,0x00) #释放按键
    #win32api.PostMessage(hwnd,win32con.WM_KEYUP,65,0xC0) #释放按键
    sleep(np.abs((rand() - 0.5) / 10) + 0.2)
コード例 #12
0
ファイル: keycodes.py プロジェクト: xorxorxorxor/rcs-db-ext
def make_key_name(vk, flags):
    # Check alt keys.
    flags_done = 0
    parts = []
    for moddata in _checks:
        for name, checkflag in moddata:
            if flags & checkflag:
                parts.append(name)
                flags_done = flags_done & checkflag
                break
    if flags_done & flags:
        parts.append(hex(flags & ~flags_done))
    # Now the key name.
    if vk is None:
        parts.append("<Unknown scan code>")
    else:
        try:
            parts.append(key_code_to_name[vk])
        except KeyError:
            # Not in our virtual key map - ask Windows what character this
            # key corresponds to.
            scancode = win32api.MapVirtualKey(vk, MAPVK_VK_TO_CHAR)
            parts.append(unichr(scancode))
    sep = "+"
    if sep in parts: sep = "-"
    return sep.join([p.capitalize() for p in parts])
コード例 #13
0
ファイル: main.py プロジェクト: blackCatx/py-Minecraft-AFK
 def get_lparam(self, wparam, isKeyUp=True):
     scanCode = win32api.MapVirtualKey(wparam, 0)
     repeatCount = 1 if isKeyUp else 0
     prevKeyState = 1 if isKeyUp else 0
     transitionState = 1 if isKeyUp else 0
     return repeatCount | (scanCode << 16) | (0 << 24) | (
         prevKeyState << 30) | (transitionState << 31)
コード例 #14
0
    def play(self):
        self.fp = subprocess.Popen(r".\freepiano\freepiano.exe")
        self._read_data(self.data_path)
        if len(self.musics) <= 0:
            print "No music file found in", self.data_path, "Exiting"
            exit(-1)

        while (True):
            time.sleep(1)
            local_cur_song = self.cur_song
            print "Playing", local_cur_song, ":", self.musics.keys(
            )[local_cur_song]

            for line in self.musics[self.musics.keys()[local_cur_song]]:
                while self.state == "pause" \
                        or str(win32gui.GetWindowText(win32gui.GetForegroundWindow())).find("piano") == -1:
                    time.sleep(1)
                if not local_cur_song == self.cur_song:
                    break
                # hardware scan code. for those with modified keyboard layout
                hwsc = win32api.MapVirtualKey(VK_CODE[line[0]], 0)
                win32api.keybd_event(VK_CODE[line[0]], hwsc, 0, 0)
                time.sleep(float(line[1]) / 1000)  # press for a long time
                win32api.keybd_event(VK_CODE[line[0]], hwsc,
                                     win32con.KEYEVENTF_KEYUP, 0)
                time.sleep(float(line[2]) / 1000)
            pass
        pass
コード例 #15
0
def Key_Init():
    '''
    Initialize data related to vks and scancodes for use at runtime.
    '''
    # Mapping of vk names to their vk codes, for convenience.
    vk_name_to_code_dict = {}

    # Set of vk codes that map to extended keys.
    vks_that_are_extended_set = set(x[0] for x in key_info_list if x[2])

    # Match vk codes to scancodes. Just do this once here, to avoid having to
    # keep doing it during runtime.
    for vkname, vk, extended, eng_scancode, local_name in key_info_list:

        # Skip unsupported keys for now.
        if not local_name:
            continue

        # For portability across languages and keyboard layouts, use windows
        # api to translate this.
        # Note: the api function always returns the non-extended scancode.
        # (See notes further below on the extended-key flag in windows.)
        # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mapvirtualkeya

        # Note: apparently MapVirtualKey is problematic for Pause and
        # returns 0, so handle manually.
        # (First google result says its a bug: https://blog.molecular-matters.com/2011/09/05/properly-handling-keyboard-input/ )
        if vkname == 'VK_PAUSE':
            scancode = eng_scancode
        else:
            # Special handling of numpad_enter; treat it like enter for
            # scancode lookup.
            this_vk = vk
            if vkname == 'NUMPAD_ENTER':
                this_vk = vk_name_to_code_dict['VK_RETURN']
            scancode = win32api.MapVirtualKey(this_vk, 0)

        # If this vk is an extended-key, set the high bit.
        if extended:
            scancode += 0x80

        vk_name_to_code_dict[vkname] = vk
        vk_to_scancode_dict[vk] = scancode
        scancode_to_name_dict[scancode] = local_name
        name_to_scancode_dict[local_name] = scancode

    # The modifier keys to always track.
    global mod_key_scancode_list
    mod_key_scancode_list = [
        name_to_scancode_dict[x] for x in [
            'alt_l',
            'alt_r',
            'ctrl_l',
            'ctrl_r',
            'shift_l',
            'shift_r',
        ]
    ]
    return
コード例 #16
0
ファイル: directkeys.py プロジェクト: c925777075/yolov5-dnf
def key_down(key):
    """
    函数功能:按下按键
    参    数:key:按键值
    """
    key = key.upper()
    vk_code = key_map[key]
    win32api.keybd_event(vk_code, win32api.MapVirtualKey(vk_code, 0), 0, 0)
コード例 #17
0
def keyPress():
    json = request.json
    key = str(json['key']).lower()
    vkCode = win32api.VkKeyScan(key)
    scanCode = win32api.MapVirtualKey(vkCode, 0)
    win32api.keybd_event(vkCode, scanCode, 0, 0)
    win32api.keybd_event(vkCode, scanCode, 2, 0)
    return 'OK'
コード例 #18
0
 def _key_up(self, key):
     """
     函数功能:抬起按键
     参    数:key:按键值
     """
     key = key.upper()
     vk_code = self.key_map[key]
     win32api.keybd_event(vk_code, win32api.MapVirtualKey(vk_code, 0), win32con.KEYEVENTF_KEYUP, 0)
コード例 #19
0
def testmove():

    x = 200
    y = 200
    duration = 1 * 100
    dx = x / duration
    dy = y / duration

    for i in range(100):
        time.sleep(0.01)
        move(dx, dy)
    click(x, y)

    win32api.keybd_event(0x53, win32api.MapVirtualKey(0x53, 0), 0, 0)
    time.sleep(0.05)
    win32api.keybd_event(0x53, win32api.MapVirtualKey(0x53, 0),
                         win32con.KEYEVENTF_KEYUP, 0)
コード例 #20
0
 def key_down(self,key):
     """
     函数功能:按下按键
     参    数:key:按键值
     """
     key = key.lower() #转小写
     vk_code = key_map[key] #获取映射值
     win32api.keybd_event(vk_code, win32api.MapVirtualKey(vk_code, 0), 0, 0) #调用系统api
コード例 #21
0
ファイル: key_event.py プロジェクト: akalinn/game_demo
def holdKey(key, durantion):

    input = []
    for i in key:
        input.append(vk_keys(i))

    for letter in input:
        win32api.keybd_event(letter, win32api.MapVirtualKey(letter, 0), 0, 0)
        sleep(np.abs((rand() - 0.5) / 10) + 0.2)

    sleep(durantion + (rand() - 0.5) / 10)

    for letter in input:
        win32api.keybd_event(letter, win32api.MapVirtualKey(letter, 0), 2,
                             0)  #释放按键
        sleep(np.abs((rand() - 0.5) / 10) + 0.2)

    sleep(np.abs((rand() - 0.5) / 10) + 0.2)
コード例 #22
0
ファイル: win32.py プロジェクト: FreelancerCommunity/flair
def virtual_key_to_name(vk) -> str:
    """Get the name of a key from its VK (virtual key) code."""
    scan_code = win32api.MapVirtualKey(vk, 0)
    # pywin32 doesn't include GetKeyNameTextW so we need to use windll
    name_buffer = ctypes.create_unicode_buffer(32)
    ctypes.windll.user32.GetKeyNameTextW((scan_code << 16 | 0 << 24 | 1 << 25),
                                         name_buffer, len(name_buffer))
    if not name_buffer.value:
        raise ValueError(f'Invalid virtual key: {vk}')
    return name_buffer.value.lower()
コード例 #23
0
def next_song(bot, update):
    chat_id = update.message.chat_id
    username = update.message.from_user.username
    if username == trustedUser:
        VK_MEDIA_NEXT_TRACK = 0xB0
        neks = win32api.MapVirtualKey(VK_MEDIA_NEXT_TRACK, 0)
        win32api.keybd_event(VK_MEDIA_NEXT_TRACK, neks)
        bot.sendMessage(chat_id, "udah next song")
    else:
        bot.sendMessage(chat_id, "ga sopan ya")
コード例 #24
0
def pause(bot, update):
    chat_id = update.message.chat_id
    username = update.message.from_user.username
    if username == trustedUser:
        VK_MEDIA_PLAY_PAUSE = 0xB3
        pause = win32api.MapVirtualKey(VK_MEDIA_PLAY_PAUSE, 0)
        win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, pause)
        bot.sendMessage(chat_id, "udah pause song (toggle sih :v)")
    else:
        bot.sendMessage(chat_id, "ga sopan ya")
コード例 #25
0
def mute(bot, update):
    chat_id = update.message.chat_id
    username = update.message.from_user.username
    if username == trustedUser:
        VK_VOLUME_MUTE = 0xAD
        mute = win32api.MapVirtualKey(VK_VOLUME_MUTE, 0)
        win32api.keybd_event(VK_VOLUME_MUTE, mute)
        bot.sendMessage(chat_id, "udah di mute")
    else:
        bot.sendMessage(chat_id, "ga sopan ya")
コード例 #26
0
def prev_song(bot, update):
    chat_id = update.message.chat_id
    username = update.message.from_user.username
    if username == trustedUser:
        VK_MEDIA_PREV_TRACK = 0xB1
        prev = win32api.MapVirtualKey(VK_MEDIA_PREV_TRACK, 0)
        win32api.keybd_event(VK_MEDIA_PREV_TRACK, prev)
        bot.sendMessage(chat_id, "udah prev song")
    else:
        bot.sendMessage(chat_id, "ga sopan ya")
コード例 #27
0
def keyboard_click(handle, key):
    time.sleep(.2)
    if isinstance(key, str) and key in printable:
        key = win32api.MapVirtualKey(ord(key), 2)
        win32api.PostMessage(handle, win32con.WM_KEYDOWN, key)
        win32api.PostMessage(handle, win32con.WM_CHAR, key)
        win32api.PostMessage(handle, win32con.WM_KEYUP, key)
    else:
        win32api.PostMessage(handle, win32con.WM_KEYDOWN, key, 0)
        win32api.PostMessage(handle, win32con.WM_KEYUP, key, 0)
コード例 #28
0
 def vk_to_char(code):
     direct = {
         win32con.VK_LEFT: '◁',
         win32con.VK_UP: '△',
         win32con.VK_RIGHT: '▷',
         win32con.VK_DOWN: '▽',
     }
     if code in direct:
         return direct[code]
     return chr(win32api.MapVirtualKey(code, MAP_VK_TO_CHAR))
コード例 #29
0
def dexMediaControl(data):
    query = data

    if 'play' in query or 'pause' in query:
        VK_MEDIA_PLAY_PAUSE = 0xB3
        hwcode = win32api.MapVirtualKey(VK_MEDIA_PLAY_PAUSE, 0)
        win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, hwcode)
    if 'stop' in query:
        VK_MEDIA_STOP = 0xB2
        hwcode = win32api.MapVirtualKey(VK_MEDIA_STOP, 0)
        win32api.keybd_event(VK_MEDIA_STOP, hwcode)
    if 'next' in query:
        VK_MEDIA_NEXT_TRACK = 0xB0
        hwcode = win32api.MapVirtualKey(VK_MEDIA_NEXT_TRACK, 0)
        win32api.keybd_event(VK_MEDIA_NEXT_TRACK, hwcode)
    if 'prev' in query:
        VK_MEDIA_PREV_TRACK = 0xB1
        hwcode = win32api.MapVirtualKey(VK_MEDIA_PREV_TRACK, 0)
        win32api.keybd_event(VK_MEDIA_PREV_TRACK, hwcode)
コード例 #30
0
def _press_key(char, game_handle=None):
    try:  #возможность запихать как букву, так и тупо номер кнопки
        char = ord(char)
    except:
        pass
    if game_handle == None:
        game_handle = wg.FindWindow(None, "Royal Quest")
    lparam_down = wa.MapVirtualKey(char, 0) * 65536 + 0x1
    lparam_up = lparam_down + 0xC0000000
    wa.PostMessage(game_handle, wc.WM_KEYDOWN, char, lparam_down)
    wa.PostMessage(game_handle, wc.WM_KEYUP, char, lparam_up)