Example #1
0
    def get_hold(self):
        # 将窗口调到前台,激活
        self.__init_handle()
        # 另起进程处理输入验证码问题
        confirm_pro = Process(target=handle_verify, args=(self.__AfxMDIFrame_hwnd, self.__hold_panel_hwnd, self.__data_grid_hwnd))
        confirm_pro.start()
        # ctrl c
        win32api.keybd_event(win32con.VK_LCONTROL, 0, 0, 0)
        # 使用 PostMessage 导致客户端退出
        # win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', win32con.SMTO_ABORTIFHUNG, 1000
        # SMTO_ABORTIFHUNG:如果接收进程处于“hung”状态,不等待超时周期结束就返回。
        # SMTO_BLOCK:阻止调用线程处理其他任何请求,直到函数返回。
        # SMTO_NORMAL:调用线程等待函数返回时,不被阻止处理其他请求。
        # SMTO_NOTIMEOUTIFNOTHUNG:Windows 95及更高版本:如果接收线程没被挂起,当超时周期结束时不返回。
        try:
            win32gui.SendMessageTimeout(self.__data_grid_hwnd, win32con.WM_KEYDOWN, win32api.VkKeyScan('c'), 0, win32con.SMTO_NORMAL, 5)
            win32gui.SendMessageTimeout(self.__data_grid_hwnd, win32con.WM_KEYUP, win32api.VkKeyScan('c'), 0, win32con.SMTO_NORMAL, 5)
        except Exception as e:
            pass
        win32api.keybd_event(win32con.VK_LCONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)

        # df = pd.read_clipboard(converters={'证券代码': str}).drop(
        #     columns=['冻结数量', '交易市场', '股东帐户', '汇率', '成本价港币', '成本价港币', '买入成本价港币', '买入在途数量', '卖出在途数量', 'Unnamed: 17', ])
        # 返回持仓数量大于 0 的股票
        # return df[df["股票余额"] > 0]
        # todo return pd.read_clipboard()
        return ''
Example #2
0
 def _char_to_keycode(cls, char):
     """
     Returns a Virtual-key Code of the character `char`.
     """
     vk_code = win32api.VkKeyScan(char)
     need_shift_key = bool(vk_code & 0x100)
     return vk_code, need_shift_key
Example #3
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'
Example #4
0
 def keyup(self):
     for key in self.keys:
     # 得到 wparam
         VkKeyCode = win32api.VkKeyScan(key)
         # 得到 lparam
         lparamUp = _get_lparam(VkKeyCode, True)
         # PostMessage
         win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, VkKeyCode, lparamUp)
         time.sleep(0.0001)
Example #5
0
    def send_string(s):
        """Send string to game"""
        for c in str(s):
            # UnityEngine.UI.InputField
            vkc = win32api.VkKeyScan(c)
            win32gui.PostMessage(Window.id, wcon.WM_KEYDOWN, vkc, 0)

            # UnityEngine.Input.GetKeyDownInt
            # https://github.com/jamesjlinden/unity-decompiled/blob/master/UnityEngine/UnityEngine/KeyCode.cs
            # Unity"s keycodes matches with ascii
            Com.shortcut(ord(c))
            time.sleep(userset.SHORT_SLEEP)
Example #6
0
    def get_hold(self):
        # 将窗口调到前台,激活
        self.__init_handle()
        # ctrl c
        win32api.keybd_event(win32con.VK_LCONTROL, 0, 0, 0)
        win32gui.PostMessage(self.__data_grid_hwnd, win32con.WM_KEYDOWN,
                             win32api.VkKeyScan('c'), 0)
        win32gui.SendMessage(self.__data_grid_hwnd, win32con.WM_KEYUP,
                             win32api.VkKeyScan('c'), 0)
        win32api.keybd_event(win32con.VK_LCONTROL, 0, win32con.KEYEVENTF_KEYUP,
                             0)

        self.__get_order_msg()

        df = pd.read_clipboard(converters={
            '证券代码': str
        }).drop(columns=[
            'Unnamed: 15',
        ])
        # 返回持仓数量大于 0 的股票
        return df[df["股票余额"] > 0]
Example #7
0
    def send_string(string: str) -> None:
        """Send one or multiple characters to the Window."""
        # Ensure it's a string by converting it to a string
        for c in str(string):
            # Make sure no key modifier is pressed
            while (win32api.GetKeyState(wcon.VK_CONTROL) < 0
                   or win32api.GetKeyState(wcon.VK_SHIFT) < 0
                   or win32api.GetKeyState(wcon.VK_MENU) < 0):
                time.sleep(0.005)

            vkc = win32api.VkKeyScan(c)  # Get virtual key code for character c
            # Only one keyup or keydown event needs to be sent
            win32gui.PostMessage(Window.id, wcon.WM_KEYDOWN, vkc, 0)
 def press_key(self, character=''):
     """
     Press a given character key.
     """
     try:
         shifted = self.is_char_shifted(character)
     except AttributeError:
         win32api.keybd_event(character, 0, 0, 0)
     else:
         if shifted:
             win32api.keybd_event(self.shift_key, 0, 0, 0)
         char_vk = win32api.VkKeyScan(character)
         win32api.keybd_event(char_vk, 0, 0, 0)
 def release_key(self, character=''):
     """
     Release a given character key.
     """
     try:
         shifted = self.is_char_shifted(character)
     except AttributeError:
         win32api.keybd_event(character, 0, KEYEVENTF_KEYUP, 0)
     else:
         if shifted:
             win32api.keybd_event(self.shift_key, 0, KEYEVENTF_KEYUP, 0)
         char_vk = win32api.VkKeyScan(character)
         win32api.keybd_event(char_vk, 0, KEYEVENTF_KEYUP, 0)
Example #10
0
    def type_text(self, string, modifiers=None):
        """
        https://mail.python.org/pipermail/python-win32/2013-July/012862.html
        https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms646304(v=vs.85).aspx
        ("MSDN: keybd_event function")
        http://stackoverflow.com/questions/4790268/how-to-generate-keystroke-combination-in-win32-api
        http://stackoverflow.com/questions/11906925/python-simulate-keydown
        http://stackoverflow.com/questions/21197257/keybd-event-keyeventf-extendedkey-explanation-required
        """
        string = str(string)

        if modifiers is not None:
            if not isinstance(modifiers, int):
                raise FailExit('incorrect modifiers = "{}"'.format(modifiers))
            for k in self.rev:
                if modifiers & k != 0:
                    self.press_key(self.key_codes[self.rev[k]][0],
                                   self.key_codes[self.rev[k]][1])
        spec_key = False
        for char in string:
            char_code = ord(char)
            if spec_key:
                spec_key = False
                self.type_char(char_code)

            elif char_code == 0:
                spec_key = True
                continue

            elif 0x20 <= char_code <= 0x7E:
                code = win32api.VkKeyScan(char)
                if code & 0x100 != 0 and modifiers is None:
                    self.press_key(self.key_codes['SHIFT'][0],
                                   self.key_codes['SHIFT'][1])

                self.type_char(code)

                if code & 0x100 != 0 and modifiers is None:
                    self.release_key(self.key_codes['SHIFT'][0],
                                     self.key_codes['SHIFT'][1])

            else:
                raise FailExit(
                    'unknown symbol "{symbol}" in "{string}"'.format(
                        symbol=str(char), string=string))

        if modifiers is not None:
            for k in self.rev:
                if modifiers & k != 0:
                    self.release_key(self.key_codes[self.rev[k]][0],
                                     self.key_codes[self.rev[k]][1])
Example #11
0
def enterURL(data):
    #press Ctrl+L
    win32api.keybd_event(win32con.VK_CONTROL, 1, 0, 0)
    win32api.keybd_event(76, 1, 0, 0)
    win32api.keybd_event(76, 1, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(win32con.VK_CONTROL, 1, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(1)
    #type the URL
    for letter in data:
        shiftPressed = False
        if letter in '~!@#$%^&*()_+{}|<>?:"ABCDEFGHIJKLMNOPQRSTUVWXYZ':
            win32api.keybd_event(win32con.VK_SHIFT, 1, 0, 0)
            shiftPressed = True
        win32api.keybd_event(win32api.VkKeyScan(letter), 0, 0, 0)
        win32api.keybd_event(win32api.VkKeyScan(letter), 0,
                             win32con.KEYEVENTF_KEYUP, 0)

        if shiftPressed == True:
            win32api.keybd_event(win32con.VK_SHIFT, 1,
                                 win32con.KEYEVENTF_KEYUP, 0)
            shiftPressed = False
    #press Enter
    win32api.keybd_event(win32con.VK_RETURN, 1, 0, 0)
    win32api.keybd_event(win32con.VK_RETURN, 1, win32con.KEYEVENTF_KEYUP, 0)
Example #12
0
def SendString(Keys):
    for c in Keys:
        cC = ord(c)
        if cC >= 0 and cC < 256:
            vk = win32api.VkKeyScan(c)
            if vk == -1:
                UniKeyPress(cC)
            else:
                if vk < 0:
                    vk = ~vk + 0x1
                shift = (vk >> 8 & 0x1 == 0x1)
                if win32api.GetKeyState(win32con.VK_CAPITAL) & 0x1 == 0x1:
                    if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'):
                        shift = not shift
                KeyPress(vk & 0xFF, shift)
        else:
            UniKeyPress(cC)
Example #13
0
def get_vk(chardesc):
    if len(chardesc) == 1:
        # it is a character.
        info = win32api.VkKeyScan(chardesc)
        if info == -1:
            return None, None
        vk = win32api.LOBYTE(info)
        state = win32api.HIBYTE(info)
        modifiers = 0
        if state & 0x1:
            modifiers |= win32con.SHIFT_PRESSED
        if state & 0x2:
            modifiers |= win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED
        if state & 0x4:
            modifiers |= win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED
        return vk, modifiers
    # must be a 'key name'
    return key_name_to_vk.get(chardesc.lower()), 0
Example #14
0
 def parseKey(self, func):
     working = self.keymap[func]
     if not working:
         logging.warning("Keyboard: Unable to parse hotkey for %s" % func)
         return
     working = working.split("+")
     for index, item in enumerate(working[0:-1]):
         if self.replacementMods.has_key(item):
             working[index] = self.replacementMods[item]
     if self.replacementKeys.has_key(working[-1]):
         working[-1] = self.replacementKeys[working[-1]]
     elif len(working[-1]) == 1:
         if working[-1].isalnum():
             working[-1] = ord(str(working[-1]).upper())
         else:
             working[-1] = win32api.VkKeyScan(str(working[-1]))
     mods = 0
     for i in working[:-1]:
         mods = mods | i
     return [mods, working[-1]]
Example #15
0
def get_vk(chardesc):
    if len(chardesc) == 1:
        # it is a character.
        info = win32api.VkKeyScan(chardesc)
        if info == -1:
            # Note: returning None, None causes an error when keyboard layout is non-English, see the report below
            # https://stackoverflow.com/questions/45138084/pythonwin-occasionally-gives-an-error-on-opening
            return 0, 0
        vk = win32api.LOBYTE(info)
        state = win32api.HIBYTE(info)
        modifiers = 0
        if state & 0x1:
            modifiers |= win32con.SHIFT_PRESSED
        if state & 0x2:
            modifiers |= win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED
        if state & 0x4:
            modifiers |= win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED
        return vk, modifiers
    # must be a 'key name'
    return key_name_to_vk.get(chardesc.lower()), 0
Example #16
0
 def _handle_key_state(key, state):
     """
     Press or release a key
     :param key: The key to press as a string (following the kivy
                 library keycodes names)
     :param state: 'release' for releasing the key otherwise it will
                   be pressed.
     """
     flags = 0
     if state == "release":
         flags = win32con.KEYEVENTF_KEYUP
         print("releasing ")
     try:
         if len(key) == 1:
             keycode = win32api.VkKeyScan(key)
         else:
             keycode = OTHER_KEYCODES[key]
     except KeyError:
         # TODO: log bad key here
         pass
     else:
         win32api.keybd_event(keycode, 0, flags, 0)
Example #17
0
 def testVkKeyScan(self):
     # hopefully ' ' doesn't depend on the locale!
     self.failUnlessEqual(win32api.VkKeyScan(' '), 32)
Example #18
0
 def testVkKeyScan(self):
     # hopefully ' ' doesn't depend on the locale!
     assert win32api.VkKeyScan(' ') == 32
Example #19
0
#win32api.keybd_event(win32con.LEFT_CTRL_PRESSED, 0, win32con.KEYEVENTF_EXTENDEDKEY,0)
#win32api.keybd_event(win32con.LEFT_ALT_PRESSED, 0, win32con.KEYEVENTF_EXTENDEDKEY,0)
#win32api.keybd_event(win32con.VK_DELETE, 0, win32con.KEYEVENTF_EXTENDEDKEY,0)

#win32api.keybd_event(win32con.LEFT_CTRL_PRESSED, 0, 0, 0)
#win32api.keybd_event(win32con.LEFT_ALT_PRESSED, 0, 0, 0)
#win32api.keybd_event(win32con.VK_DELETE, 0, 0, 0)

#win32api.keybd_event(win32con.LEFT_CTRL_PRESSED | win32con.LEFT_ALT_PRESSED | win32con.VK_DELETE, 0, 0, 0)

win32api.keybd_event(win32con.VK_LWIN, 0, 0, 0)
win32api.keybd_event(338, 0, 0, 0)
time.sleep(1)

#win32api.keybd_event(win32con.SHIFT_PRESSED, 0, win32con.KEYEVENTF_KEYUP,0)
#win32api.keybd_event(win32con.LEFT_CTRL_PRESSED, 0, win32con.KEYEVENTF_KEYUP,0)
#win32api.keybd_event(win32con.LEFT_ALT_PRESSED, 0, win32con.KEYEVENTF_KEYUP,0)
#win32api.keybd_event(win32con.VK_DELETE, 0, win32con.KEYEVENTF_KEYUP,0)

win32api.keybd_event(win32con.VK_LWIN, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(338, 0, win32con.KEYEVENTF_KEYUP, 0)

#print(win32con.__dict__)

for entry in win32con.__dict__:
    #print(entry)
    if entry.startswith('VK_') or entry.startswith('KEYEVENT'):
        print(entry)

print(win32api.VkKeyScan('R'))
Example #20
0
KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS,
KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT,
KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE
""".split(","))]

keysmap3 = map(lambda a: ("pygame.KMOD_" + a[0], a[0]),
  filter(lambda a: "KMOD_" + a[0] in kmods,
         [ ("LCTRL", 0x01), ("LSHIFT", 0x02), ("LALT", 0x04),
           ("LMETA", 0x08), ("RCTRL", 0x10), ("RSHIFT", 0x20),
           ("RALT", 0x40), ("RMETA", 0x80) ])
)

import win32api, win32con

keystrokesdata = (
  ("A", "a", win32api.VkKeyScan("a"), "a"), ("B", "b", win32api.VkKeyScan("b"), "b"), ("C", "c", win32api.VkKeyScan("c"), "c"), ("D", "d", win32api.VkKeyScan("d"), "d"), 
  ("E", "e", win32api.VkKeyScan("e"), "e"), ("F", "f", win32api.VkKeyScan("f"), "f"), ("G", "g", win32api.VkKeyScan("g"), "g"), ("H", "h", win32api.VkKeyScan("h"), "h"), 
  ("I", "i", win32api.VkKeyScan("i"), "i"), ("J", "j", win32api.VkKeyScan("j"), "j"), ("K", "k", win32api.VkKeyScan("k"), "k"), ("L", "l", win32api.VkKeyScan("l"), "l"), 
  ("M", "m", win32api.VkKeyScan("m"), "m"), ("N", "n", win32api.VkKeyScan("n"), "n"), ("O", "o", win32api.VkKeyScan("o"), "o"), ("P", "p", win32api.VkKeyScan("p"), "p"), 
  ("Q", "q", win32api.VkKeyScan("q"), "q"), ("R", "r", win32api.VkKeyScan("r"), "r"), ("S", "s", win32api.VkKeyScan("s"), "s"), ("T", "t", win32api.VkKeyScan("t"), "t"),
  ("U", "u", win32api.VkKeyScan("u"), "u"), ("V", "v", win32api.VkKeyScan("v"), "v"), ("W", "w", win32api.VkKeyScan("w"), "w"), ("X", "x", win32api.VkKeyScan("x"), "x"), 
  ("Y", "y", win32api.VkKeyScan("y"), "y"), ("Z", "z", win32api.VkKeyScan("z"), "z"), ("ONE", "1", win32api.VkKeyScan("1"), "1"), ("TWO", "2", win32api.VkKeyScan("2"), "2"), 
  ("THREE", "3", win32api.VkKeyScan("3"), "3"), ("FOUR", "4", win32api.VkKeyScan("4"), "4"), ("FIVE", "5", win32api.VkKeyScan("5"), "5"), 
  ("SIX", "6", win32api.VkKeyScan("6"), "6"), 
  ("SEVEN", "7", win32api.VkKeyScan("7"), "7"), ("EIGHT", "8", win32api.VkKeyScan("8"), "8"), ("NINE", "9", win32api.VkKeyScan("9"), "9"), 
  ("ZERO", "0", win32api.VkKeyScan("0"), "0"), ("DOT", ".", win32api.VkKeyScan("."), "."), ("COMMA", ",", win32api.VkKeyScan(","), ","), 
  ("QUESTION", "?", win32api.VkKeyScan("?"), "?"), ("EXCLAMATION", "!", win32api.VkKeyScan("!"), "!"), ("COLON", ":", win32api.VkKeyScan(":"), ":"), 
  ("SEMICOLON", ";", win32api.VkKeyScan(";"), ";"), ("AT", "@", win32api.VkKeyScan("@"), "@"), ("BASH", "#", win32api.VkKeyScan("#"), "#"),
  ("DOLLAR", "$", win32api.VkKeyScan("$"), "$"), ("PERCENT", "%", win32api.VkKeyScan("%"), "%"), ("AMPERSAND", "&", win32api.VkKeyScan("&"), "&"), 
  ("STAR", "*", win32con.VK_MULTIPLY, "*"), ("PLUS", "+", win32con.VK_ADD, "+"), ("MINUS", "-", win32con.VK_SUBTRACT, "-"), 
  ("EQUALS", "=", win32api.VkKeyScan("="), "="), ("FSLASH", "/", win32api.VkKeyScan("/"), "/"), ("BSLASH", "\\", win32api.VkKeyScan("\\"), "\\"), 
Example #21
0
 def key_press(self, key):
     vk_code = win32api.VkKeyScan(str(key))
     scan_code = win32api.MapVirtualKey(vk_code, 0)
     win32api.keybd_event(vk_code, scan_code, 0, 0)
     win32api.keybd_event(vk_code, scan_code, 2, 0)
     return True
Example #22
0
 def testVkKeyScan(self):
     # hopefully ' ' doesn't depend on the locale!
     self.assertEqual(win32api.VkKeyScan(" "), 32)
Example #23
0
 def exceptkeys_Vk(self):
     for key in self.exceptkeys:
         if key in KB_VK_MAP:
             yield KB_VK_MAP[key]
         else:
             yield win32api.VkKeyScan(key)
Example #24
0
def OnKeyboardEvent(event):
    if (event.KeyID == 118 or event.KeyID == 119 or event.KeyID == 120
            or event.KeyID == 121 or event.KeyID == 122 or event.KeyID == 123):
        pasteFlag = 0
        ##        print('MessageName:',event.MessageName)
        ##        print('Message:',event.Message)
        ##        print('Time:',event.Time)
        ##        print('Window:',event.Window)
        ##        print('WindowName:',event.WindowName)
        ##        print('Ascii:', event.Ascii, chr(event.Ascii))
        ##        print('Key:', event.Key)
        ##        print('KeyID:', event.KeyID)
        ##        print('ScanCode:', event.ScanCode)
        ##        print('Extended:', event.Extended)
        ##        print('Injected:', event.Injected)
        ##        print('Alt', event.Alt)
        ##        print('Transition', event.Transition)
        ##        print('---')
        # return True to pass the event to other handlers

        ##    hwnd = win32gui.GetForegroundWindow()
        ##    print(win32gui.GetWindowText(hwnd))
        if event.KeyID == 118 or event.KeyID == 119 or event.KeyID == 120 or event.KeyID == 121 or event.KeyID == 122:  #F7 ... F11
            ##        win32api.keybd_event(0x46, 0, ) # F
            ##        win32api.keybd_event(0x52, 0, ) # R
            ##        win32api.keybd_event(0x0D, 0, ) # R

            win32api.keybd_event(win32con.VK_CONTROL, 0x9d, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('C'), 0x9e, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('C'), 0x9e,
                                 win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(win32con.VK_CONTROL, 0x9d,
                                 win32con.KEYEVENTF_KEYUP, 0)
            #----------------------------
            time.sleep(0.01)
            OpenClipboard()
            value = GetClipboardData()
            #========
            if event.KeyID == 118:  #F7 key end with _000
                foundKey = PosMulti00_commonJobs.findCorrespondentKey(
                    dataDict, value, labelLoweredStandardedDict)
                outputstring = re.sub('_000\d', '_0000', foundKey)
                pasteFlag = 1
            elif event.KeyID == 119:  #F8 keep the key
                foundKey = PosMulti00_commonJobs.findCorrespondentKey(
                    dataDict, value, labelLoweredStandardedDict)
                outputstring = foundKey
                pasteFlag = 1
            elif event.KeyID == 121:  #F10 keep the key
                foundKey = PosMulti00_commonJobs.findCorrespondentKey(
                    dataDict, value, labelLoweredStandardedDict)
                foundKey = re.sub('_000\d', '_0000', foundKey)
                outputstring = '<posui:showLabel key="' + foundKey + '" />'
                pasteFlag = 1
            elif event.KeyID == 122:  #F11 header value with tooltip ; input value MUST start with > character
                if re.search(r'^>', value):
                    value = value.lstrip(">")
                    foundKey = PosMulti00_commonJobs.findCorrespondentKey(
                        dataDict, value, labelLoweredStandardedDict)
                    toolTip = re.sub('_000\d', '_0000', foundKey)
                    outputstring = ' onmouseover="tooltipOn(\'<posui:showLabel key="' + toolTip + '" />\');" onmouseout="tooltipOff();"><posui:showLabel key="' + foundKey + '" />'
                    pasteFlag = 1
                else:
                    outputstring = value
                    pasteFlag = 0

            #========
            SetClipboardData(CF_UNICODETEXT, outputstring)
            CloseClipboard()
            #----------------------------
            if pasteFlag == 1:
                win32api.keybd_event(win32con.VK_CONTROL, 0x9d, 0, 0)
                win32api.keybd_event(win32api.VkKeyScan('V'), 0x9e, 0, 0)
                win32api.keybd_event(win32api.VkKeyScan('V'), 0x9e,
                                     win32con.KEYEVENTF_KEYUP, 0)
                win32api.keybd_event(win32con.VK_CONTROL, 0x9d,
                                     win32con.KEYEVENTF_KEYUP, 0)

        elif event.KeyID == 123:  #F12
            hm.UnhookKeyboard()

    return True
Example #25
0
def TypeString(string_to_type,
               use_modifiers=False,
               keystroke_time=0,
               time_between_keystrokes=0):
    """Simulate typing a string on the keyboard.

  Args:
    string_to_type: the string to print
    use_modifiers: specifies whether the following modifier characters
      should be active:
      {abc}: type characters with ALT held down
      [abc]: type characters with CTRL held down
      \ escapes {}[] and treats these values as literal
      standard escape sequences are valid even if use_modifiers is false
      \p is "pause" for one second, useful when driving menus
      \1-\9 is F-key, \0 is F10

      TODO(jhaas): support for explicit control of SHIFT, support for
                   nonprintable keys (F-keys, ESC, arrow keys, etc),
                   support for explicit control of left vs. right ALT or SHIFT,
                   support for Windows key

    keystroke_time: length of time (in secondes) to "hold down" the key
    time_between_keystrokes: length of time (seconds) to pause between keys

  Returns:
    None
  """

    shift_held = win32api.GetAsyncKeyState(win32con.VK_SHIFT) < 0
    ctrl_held = win32api.GetAsyncKeyState(win32con.VK_CONTROL) < 0
    alt_held = win32api.GetAsyncKeyState(win32con.VK_MENU) < 0

    next_escaped = False
    escape_chars = {
        'a': '\a',
        'b': '\b',
        'f': '\f',
        'n': '\n',
        'r': '\r',
        't': '\t',
        'v': '\v'
    }

    for char in string_to_type:
        vk = None
        handled = False

        # Check to see if this is the start or end of a modified block (that is,
        # {abc} for ALT-modified keys or [abc] for CTRL-modified keys
        if use_modifiers and not next_escaped:
            handled = True
            if char == "{" and not alt_held:
                alt_held = True
                PressKey(True, win32con.VK_MENU)
            elif char == "}" and alt_held:
                alt_held = False
                PressKey(False, win32con.VK_MENU)
            elif char == "[" and not ctrl_held:
                ctrl_held = True
                PressKey(True, win32con.VK_CONTROL)
            elif char == "]" and ctrl_held:
                ctrl_held = False
                PressKey(False, win32con.VK_CONTROL)
            else:
                handled = False

        # If this is an explicitly-escaped character, replace it with the
        # appropriate code
        if next_escaped and char in escape_chars: char = escape_chars[char]

        # If this is \p, pause for one second.
        if next_escaped and char == 'p':
            time.sleep(1)
            next_escaped = False
            handled = True

        # If this is \(d), press F key
        if next_escaped and char.isdigit():
            fkey = int(char)
            if not fkey: fkey = 10
            next_escaped = False
            vk = win32con.VK_F1 + fkey - 1

        # If this is the backslash, the next character is escaped
        if not next_escaped and char == "\\":
            next_escaped = True
            handled = True

        # If we make it here, it's not a special character, or it's an
        # escaped special character which should be treated as a literal
        if not handled:
            next_escaped = False
            if not vk: vk = win32api.VkKeyScan(char)

            # VkKeyScan() returns the scan code in the low byte. The upper
            # byte specifies modifiers necessary to produce the given character
            # from the given scan code. The only one we're concerned with at the
            # moment is Shift. Determine the shift state and compare it to the
            # current state... if it differs, press or release the shift key.
            new_shift_held = bool(vk & (1 << 8))

            if new_shift_held != shift_held:
                PressKey(new_shift_held, win32con.VK_SHIFT)
                shift_held = new_shift_held

            # Type the key with the specified length, then wait the specified delay
            TypeKey(vk & 0xFF, keystroke_time)
            time.sleep(time_between_keystrokes)

    # Release the modifier keys, if held
    if shift_held: PressKey(False, win32con.VK_SHIFT)
    if ctrl_held: PressKey(False, win32con.VK_CONTROL)
    if alt_held: PressKey(False, win32con.VK_MENU)
Example #26
0
                # 提示  弹出框, 使用ocr识别
                identify_code = ocr_string_from_hwnd(prompt_info["image"],
                                                     expand=10)
                win32gui.SendMessage(prompt_info["input"], win32con.WM_SETTEXT,
                                     None, identify_code)
                win32api.PostMessage(prompt_info["confirm_btn"],
                                     win32con.WM_LBUTTONDOWN, None, None)
                win32api.PostMessage(prompt_info["confirm_btn"],
                                     win32con.WM_LBUTTONUP, None, None)
                return


if __name__ == '__main__':
    hwnd = win32gui.FindWindow("#32770", "Save As")
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.SetForegroundWindow(hwnd)

    win32gui.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, win32con.VK_MENU,
                         0x20380001)
    # win32gui.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, win32api.VkKeyScan('s'), 1 << 29)
    win32gui.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, win32api.VkKeyScan('s'),
                         0x20200001)
    win32gui.PostMessage(hwnd, win32con.WM_SYSCHAR, 0x76, 0x20200001)
    time.sleep(0.05)
    win32gui.PostMessage(hwnd, win32con.WM_SYSKEYUP, win32api.VkKeyScan('s'),
                         0xE0200001)
    win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_MENU, 0xC0380001)

    pass
Example #27
0
 def lookup_keycode_value(self, character):
     """ Helper method to lookup a keycode from a character """
     return win32api.VkKeyScan(character)
Example #28
0
def kb_event(k):
    global speed
    i = 0
    while i < len(k):
        win32api.GetAsyncKeyState(win32con.VK_ESCAPE)  #clear
        if win32api.GetAsyncKeyState(win32con.VK_ESCAPE):  #stop
            #if speed>0: speed=0
            break

        if k[i] == '<' and len(k) != 1:
            #cases ??
            if k[i + 1] == ',':
                if k[i:i + 3] == '<,>':
                    time.sleep(0.150)
                    k = k[k.find('>') + 1:len(k)]  #re i
                    continue
            #if k[i+1]=='a':
            #
            if k[i + 1] == 'b':
                if k[i:i + 4] == '<bs>':
                    kb_press(win32con.VK_BACK, 1)
                    k = k[k.find('>') + 1:len(k)]
                    continue
                if k[i:i + 4] == '<bs*':
                    n = int(k[k.find('*') + 1:k.find('>')])  #get num
                    kb_press(win32con.VK_BACK, n)
                    k = k[k.find('>') + 1:len(k)]
                    continue
            #if k[i+1]=='c':
            #
            if k[i + 1] == 's':
                if k[i:i + 7] == '<sleep:':
                    n = int(k[k.find(':') + 1:k.find('>')])
                    time.sleep(n)
                    k = k[k.find('>') + 1:len(k)]
                    continue
                if k[i:i + 7] == '<speed:':
                    n = int(k[k.find(':') + 1:k.find('>')])
                    speed = n
                    k = k[k.find('>') + 1:len(k)]
                    continue

            #connect
            if k.find(':>') or k.find('->') and k.find('<', 1) < (
                    k.find(':>') or k.find('->')) and (k[1] != ':'
                                                       or k[1] != '-'):
                con = k[0:k.find('>') + 1]  #<x:> or <x->
                global database
                with open(database) as db:
                    for cell in db:
                        if cell[0:len(con)] == con:
                            p = k[len(con):len(k)]  #pre
                            o = cell[len(con):len(cell)]
                            if o[-1] == '\n': o = cell[len(con):len(cell) - 1]
                            k = o + p
                            db.close()
                            break

        shift = False  #init shift hold
        x = k[i]  #init ord
        if ((ord(x) >= 33 and ord(x) <= 38) or (ord(x) >= 40 and ord(x) <= 43)
                or ord(x) == 58 or ord(x) == 60
                or (ord(x) >= 62 and ord(x) <= 91) or ord(x) == 94
                or ord(x) == 95
                or (ord(x) >= 123 and ord(x) <= 126)):  #if must hold shift
            shift = True
        if shift: win32api.keybd_event(win32con.VK_LSHIFT, 0, 1, 0)
        win32api.keybd_event(win32api.VkKeyScan(x), 0, 0, 0)  #kb press
        win32api.keybd_event(win32api.VkKeyScan(x), 0, 2, 0)  #kb release
        if shift:
            win32api.keybd_event(win32con.VK_LSHIFT, 0, 2, 0)
            win32api.keybd_event(win32con.VK_RSHIFT, 0, 2, 0)
        if speed > 0: time.sleep(speed)
        k = k[1:len(k)]  #++
Example #29
0
# Shorthand
def vk2vsc(vk):
    return win32api.MapVirtualKey(vk, MAPVK_VK_TO_VSC)


def vsc2vk(vsc):
    return win32api.MapVirtualKey(vsc, MAPVK_VSC_TO_VK)


# build scan and shifted-scan map mapping scaancode -> character
scans = {}
shifted_scans = {}
# We only care about printable characters
for k in xrange(0x20, 0x7f):
    vk = win32api.VkKeyScan(chr(k))  # Char->VK using current layout
    if vk & ~0x1ff:
        continue
    if vk & 0x100:
        # shifted
        shifted_scans[vk2vsc(vk & 0xff)] = chr(k)
    else:
        scans[vk2vsc(vk)] = chr(k)

# add symbolic keys
for vn in filter(lambda x: x.startswith('VK_'), dir(win32con)):
    vk = getattr(win32con, vn)
    scan = vk2vsc(vk)
    if not scan in scans:
        scans[scan] = '<' + vn[3:] + '>'