def onFocusGainedWin(note, num):
    if num == 0:
        win32api.LoadKeyboardLayout(
            localIdent2Name[mw.col.decks.confForDid(
                mw.col.decks.current()['id']).get('questionLayout',
                                                  startLayout)], 1)
    elif num == 1:
        win32api.LoadKeyboardLayout(
            localIdent2Name[mw.col.decks.confForDid(
                mw.col.decks.current()['id']).get('answerLayout',
                                                  startLayout)], 1)
Exemple #2
0
    def wrapper(*args, **kwargs):
        if win32api.LoadKeyboardLayout('0x0409',
                                       win32con.KLF_ACTIVATE) == None:
            return Exception('加载键盘失败')
        # 语言代码
        # https://msdn.microsoft.com/en-us/library/cc233982.aspx
        LID = {
            0x0804: "Chinese (Simplified) (People's Republic of China)",
            0x0409: 'English (United States)'
        }

        # 获取前景窗口句柄
        hwnd = win32gui.GetForegroundWindow()

        # 获取前景窗口标题
        title = win32gui.GetWindowText(hwnd)
        # 获取键盘布局列表
        im_list = win32api.GetKeyboardLayoutList()
        im_list = list(map(hex, im_list))
        print(im_list)
        oldKey = hex(win32api.GetKeyboardLayout())

        # 设置键盘布局为英文
        result = win32api.SendMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, 0,
                                      0x4090409)
        if result == 0:
            print('设置英文键盘成功!')

        inner(*args, *kwargs)

        result = win32api.SendMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, 0,
                                      oldKey)
        if result == 0:
            print('还原键盘成功!')
Exemple #3
0
    def send_keys_to_input(
        self,
        keys_to_type: str,
        with_enter: bool = True,
        send_delay: float = 0.5,
        enter_delay: float = 1.5,
    ) -> None:
        """Send keys to windows and add ENTER if `with_enter` is True

        At the end of send_keys there is by default 1.0 second delay.
        At the end of ENTER there is by default 3.5 second delay.

        :param keys_to_type: keys to type into Windows
        :param with_enter: send ENTER if `with_enter` is True
        :param send_delay: delay after send_keys
        :param enter_delay: delay after ENTER
        """
        # Set keyboard layout for Windows platform
        if platform.system() == "Windows":
            win32api.LoadKeyboardLayout("00000409", 1)

        self.send_keys(keys_to_type)
        delay(send_delay)
        if with_enter:
            self.send_keys("{ENTER}")
            delay(enter_delay)
Exemple #4
0
 def login(self):
     # to log in id
     # should check size ration of the login window of btnet. Normal 4, other 5  ********************
     pyautogui.keyDown('shift')
     time.sleep(0.2)
     pyautogui.press('tab')
     time.sleep(0.2)
     pyautogui.keyUp('shift')
     time.sleep(random.uniform(3.0, 5.0) / 10)
     # clear box
     pyautogui.press('backspace')
     time.sleep(random.uniform(3.0, 5.0) / 10)
     # change to english
     pyautogui.press('shift')
     time.sleep(random.uniform(3.0, 5.0) / 10)
     win32api.LoadKeyboardLayout('00000409', 1)
     time.sleep(random.uniform(3.0, 5.0) / 10)
     # type in
     pyautogui.typewrite(self.userName, interval=(random.randint(15, 30) / 100))
     time.sleep((random.uniform(15.0, 30.0) / 100))
     pyautogui.press('tab')
     pyautogui.typewrite(self.userPwd, interval=(random.randint(15, 30) / 100))
     time.sleep(13)
     for i in range(3):
         pyautogui.press('tab')
         time.sleep(random.uniform(3.0, 5.0) / 10)
     # log in
     pyautogui.press('enter')
     return
 def login(self):
     # to log in id
     for i in range(4):  # orginal 4
         pyautogui.press('tab')
         time.sleep(random.randint(3, 5) / 10)
     # clear box
     pyautogui.press('backspace')
     time.sleep(random.randint(3, 5) / 10)
     # change to english
     pyautogui.press('shift')
     time.sleep(random.randint(3, 5) / 10)
     win32api.LoadKeyboardLayout('00000409', 1)
     time.sleep(random.randint(3, 5) / 10)
     # typein
     pyautogui.typewrite(self.userName,
                         interval=(random.randint(15, 30) / 100))
     time.sleep((random.randint(15, 30) / 100))
     pyautogui.press('tab')
     pyautogui.typewrite(self.userPwd,
                         interval=(random.randint(15, 30) / 100))
     time.sleep(13)
     for i in range(3):
         pyautogui.press('tab')
         time.sleep(random.randint(3, 5) / 10)
     # log in
     pyautogui.press('enter')
     return
Exemple #6
0
 def set(self, _im):
     hkl = win32api.LoadKeyboardLayout(_im[0], win32con.KLF_ACTIVATE)
     print hkl
     #if hkl is None
     #return -2
     #else
     win32api.ActivateKeyboardLayout(
         hkl, win32con.KLF_SETFORPROCESS)  # Active ime
def restoreOrigLayout(self=None):
    if isLin:
        subprocess.run(["setxkbmap", startLayout, startVariant])
    elif isWin:
        currentLayoutList = win32api.GetKeyboardLayoutList()
        win32api.LoadKeyboardLayout(startLayout, 1)
        # remove layouts loaded by Anki
        for layout in currentLayoutList:
            if layout not in loadedLayouts:
                if not UnloadKeyboardLayout(layout):
                    raise Exception("Could not unload Layout")
Exemple #8
0
    def btn_add_plateg(self):
        self.win_add = UiWinAdd()
        self.win_add.name_plateg()

        if win32api.GetKeyboardLayout() == 67699721:  # 67699721 - английский 00000409
            win32api.LoadKeyboardLayout("00000419", 1)  # 68748313 - русский    00000419

        # КНОПКИ окна ДОБАВЛЕНИЕ ПЛАТЕЖА
        self.win_add.btn_OK.clicked.connect(self.win_add_name_ok)  # кнопка OK окна ИМЯ
        self.win_add.btn_OK.setAutoDefault(True)
        self.win_add.lineEdit.returnPressed.connect(self.win_add.btn_OK.click)

        self.win_add.btn_Cancel.clicked.connect(self.win_add_name_cancel)  # кнопка CANCEL
Exemple #9
0
    def win_add_name_ok(self):
        self.name = self.win_add.lineEdit.text()

        self.win_add.lineEdit.clear()
        self.win_add.close()

        self.summ_plat = UiWinAdd()
        self.summ_plat.name_plateg()
        self.summ_plat.label.setText("Сумма платежа")

        if win32api.GetKeyboardLayout() == 68748313:  # 67699721 - английский 00000409
            win32api.LoadKeyboardLayout("00000409", 1)  # 68748313 - русский    00000419

        self.summ_plat.btn_OK.clicked.connect(self.win_add_summ_ok)  # кнопка OK окна СУММА
        self.summ_plat.btn_OK.setAutoDefault(True)
        self.summ_plat.lineEdit.returnPressed.connect(self.summ_plat.btn_OK.click)

        self.summ_plat.btn_Cancel.clicked.connect(self.win_add_summ_cancel)
Exemple #10
0
def tagKeyHandler(self, event, _old):
    """Wrap default _keyHandler with new keybindings."""
    key = unicode(event.text())
    note = mw.reviewer.card.note()
    if tag_dialog_shortcut and key in tag_dialog_shortcut:
        mw.checkpoint(_("Edit Tags"))
        import win32api
        win32api.LoadKeyboardLayout('00000409', 1)  # to switch to english
        edit_tag_dialog(note)
    elif key in tag_shortcuts:
        binding = tag_shortcuts[key]
        if 'action' not in binding:
            binding['action'] = 'add'

        if ('after' in binding
                and binding['after'] in ['suspend', 'suspend-note']):
            mw.checkpoint("Edit Tags and Suspend Note")
            tooltip_message = 'Suspended note and edited tags: {}'
            self.mw.col.sched.suspendCards(
                [card.id for card in self.card.note().cards()])
        elif 'after' in binding and binding['after'] in ['bury', 'bury-note']:
            mw.checkpoint("Edit Tags and Bury Note")
            tooltip_message = 'Buried note and edited tags: {}'
            mw.col.sched.buryNote(note.id)
        elif 'after' in binding and binding['after'] == 'suspend-card':
            mw.checkpoint("Edit Tags and Suspend Card")
            tooltip_message = 'Suspended card and edited tags: {}'
            self.mw.col.sched.suspendCards([self.card.id])
        elif 'after' in binding and binding['after'] == 'bury-card':
            mw.checkpoint("Edit Tags and Bury Card")
            tooltip_message = 'Buried card and edited tags: {}'
            mw.col.sched.buryCards([self.card.id])
        else:
            mw.checkpoint(_("edit Tags"))
            tooltip_message = 'Edited tags: {}'
        tag_edits = edit_note_tags(note, binding['tags'], binding['action'])
        if 'after' in binding:
            mw.reset()
        else:
            redraw_card()
        tooltip(tooltip_message.format(tag_edits))
    else:
        _old(self, event)
Exemple #11
0
def set_keyboard(id=67699721):

    win32api.LoadKeyboardLayout('00000409', 1)  # to switch to english

    user32 = ctypes.WinDLL('user32', use_last_error=True)
    curr_window = user32.GetForegroundWindow()
    thread_id = user32.GetWindowThreadProcessId(curr_window, 0)
    klid = user32.GetKeyboardLayout(thread_id)

    while (1):
        if klid != 67699721:
            hotkey('alt', 'shift')
            user32 = ctypes.WinDLL('user32', use_last_error=True)
            curr_window = user32.GetForegroundWindow()
            thread_id = user32.GetWindowThreadProcessId(curr_window, 0)
            klid = user32.GetKeyboardLayout(thread_id)
        else:
            logger.info('Language set')
            break
Exemple #12
0
    def win_add_name_ok(self):
        self.radio_plat.close()

        if win32api.GetKeyboardLayout(
        ) == 67699721:  # 67699721 - английский 00000409
            win32api.LoadKeyboardLayout("00000419",
                                        1)  # 68748313 - русский    00000419

        self.win_add = UiWinAdd()
        self.win_add.name_plateg()

        self.name = self.win_add.lineEdit.text()

        self.win_add.btn_OK.clicked.connect(self.win_add_summ_ok)  # кнопка OK
        self.win_add.btn_OK.setAutoDefault(True)
        self.win_add.lineEdit.returnPressed.connect(self.win_add.btn_OK.click)

        self.win_add.btn_Cancel.clicked.connect(
            self.win_add_name_cancel)  # кнопка CANCEL
Exemple #13
0
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
Exemple #14
0
    def text_editing(self, lineEdit_sum):
        try:
            if win32api.GetKeyboardLayout() == 68748313:  # 67699721 - английский 00000409
                win32api.LoadKeyboardLayout("00000409", 1)  # 68748313 - русский    00000419

            self.label_ERROR_KP.clear()
            self.checkBox_Edit_KP.show()
            year = self.comboBox_year_KP.currentText()

            if lineEdit_sum == self.lineEdit_sum_Power:
                self.sum_platega(self.dict_pole, 'Электричество', year)
            elif lineEdit_sum == self.lineEdit_sum_Water:
                self.sum_platega(self.dict_pole, 'Вода', year)
            elif lineEdit_sum == self.lineEdit_sum_Gaz:
                self.sum_platega(self.dict_pole, 'Газ', year)
            elif lineEdit_sum == self.new_p.lineEdit_sum_Plat:
                v = self.dict_pole.get(self.new_p.label_Plat.text())
                pl_sum = float(v.text())
                list_pl = pl_sum, 0, 0
                self.dop_plategi[self.new_p.label_Plat.text()] = list_pl

                def ok():
                    den_ok = denominacia(year, pl_sum)
                    v.setText(den_ok + " руб")

                v.returnPressed.connect(ok)

            self.plategi_sum = 0

            for i, j in self.dop_plategi.items():
                self.plategi_sum += float(j[0]) if type(j) == tuple else float(j)

            self.itog_sum(self.plategi_sum)

        except ValueError:
            self.checkBox_Edit_KP.hide()
            self.label_ERROR_KP.setText('Должно быдь значение!')
Exemple #15
0
def newKeyHandler(self, evt):
    key = unicode(evt.text())
    card = mw.reviewer.card
    if not key:
        origKeyHandler(self, evt)
        return
    elif key == reschedule_shortcut:
        mw.checkpoint(_("Reschedule card"))
        promptNewInterval(self, card)
        #    elif key == reschedule_four_weeks:
        #mw.checkpoint(_("Reschedule card"))
        #mw.col.sched.reschedCards( [card.id], 21, 42 )
        #tooltip('Rescheduled for review in 3-6 weeks'  )
        #mw.reset()
    elif key == reschedule_tomorrow:
        mw.checkpoint(_("Reschedule card"))
        mw.col.sched.reschedCards( [card.id], 1, 1 )
        tooltip('Rescheduled for review tomorrow'  )
        mw.reset()
    elif key in edit_occupyImage:
        patt=r"""<img.*?src=(["'])(.*?)\1"""
        pattern = re.compile(patt, flags=re.I|re.M|re.S)
        note = mw.reviewer.card.note()
        field_names = [item[0] for item in note.items()]
        imagename=""
        field_name=""
        valid_ext=False
        for fldName in field_names:
            m = pattern.search(note[fldName])
            if(m):
                imagename = m.group(2)
                valid_ext = imagename.endswith((".jpg",".jpeg",".gif",".png"))
                if(valid_ext):
                    field_name=fldName
                    break
        if(valid_ext):
            try:
                mw.reviewer.image_occlusion
            except:
                mw.reviewer.image_occlusion = ImageOcc_Add(mw.reviewer)
                
            mw.reviewer.image_occlusion.add_notes(field_name)
    elif key in edit_rtl:
        mw.checkpoint(_("Made RTL"))
        note = mw.reviewer.card.note()
        for item in note.items():
            if item[0] in rtl_fileds_arr:
                note[item[0]] = "<div class='f r'>" + note[item[0]] + "</div>"
                note.flush()
                redraw_card()
    elif key in key_add_note :
        if key!="N":
            import win32api
            win32api.LoadKeyboardLayout('00000429',1) # to switch to english
        text, ok = getText("your note on this card?")
        if ok:
            note = mw.reviewer.card.note()
            for item in note.items():
                if item[0] in rtl_fileds_arr:
                    note[item[0]] = note[item[0]] + "<p class=\"%(className)s\">%(text)s</p>" % \
                        {'className':"floatLeft" if key=="N" else "f r",
                        'text':text}
                    note.flush()
                    redraw_card()
    elif key in key_english:
        import win32api
        win32api.LoadKeyboardLayout('00000409',1) # to switch to english
    else:
        origKeyHandler(self, evt)
Exemple #16
0
 def set(self, _im):
     win32api.LoadKeyboardLayout(_im[0], win32con.KLF_ACTIVATE)
Exemple #17
0
    def read_pokaz_schet(self):
        if win32api.GetKeyboardLayout(
        ) == 68748313:  # 67699721 - английский 00000409
            win32api.LoadKeyboardLayout("00000409",
                                        1)  # 68748313 - русский    00000419

        file_db = open('Komunal.db', 'a')  # открываем файл базы данных
        file_db.close()
        self.data_base = 'Komunal.db'  # имя базы данных
        table = 'Pokazanya_year_' + str(
            self.comboBox_year_PS.currentText())  # имя таблицы
        col_name = 'id'  # Имя колонки

        heading = (
            'id integer primary key , month_year text, Pred_PW integer, Actual_PW integer, Pred_WA_1 integer, '
            'Actual_WA_1 integer, Pred_WA_2 integer, Actual_WA_2 integer, Pred_WA_3 integer, '
            'Actual_WA_3 integer, Pred_WA_4 integer, Actual_WA_4 integer, Pred_GZ integer, Actual_GZ integer, '
            'PW_month_ras integer, WA_C_month_ras integer, WA_H_month_ras integer, WA_month_ras integer, '
            'GZ_month_ras integer')

        # это нужно если база данных отсутствует
        sqlite3_create_db(self.data_base, table,
                          heading)  # создаем таблицу в базе данных

        # очищаем поля окна ПОКАЗАНИЯ СЧЕТЧИКОВ
        win_pole = [
            self.lineEdit_pred_pokaz_P, self.lineEdit_post_pokaz_P,
            self.lineEdit_pred_pokaz_W1, self.lineEdit_post_pokaz_W1,
            self.lineEdit_pred_pokaz_W2, self.lineEdit_post_pokaz_W2,
            self.lineEdit_pred_pokaz_W3, self.lineEdit_post_pokaz_W3,
            self.lineEdit_pred_pokaz_W4, self.lineEdit_post_pokaz_W4,
            self.lineEdit_pred_pokaz_G, self.lineEdit_post_pokaz_G,
            self.label_month_ras_P, self.label_month_ras_WC,
            self.label_month_ras_WH, self.label_month_ras,
            self.label_month_ras_G, self.label_ERROR_PS, self.label_OK_PS
        ]

        for i in win_pole:
            i.clear()

        self.checkBox_Edit_PS.show()

        if self.comboBox_month_PS.currentIndex() + 1 in sqlite3_read_db(
                self.data_base, table, col_name)[0]:
            self.label_OK_PS.setPixmap(
                QtGui.QPixmap("./Resource/img/Galochka.png"))

        if not sqlite3_read_db(self.data_base, table)[0] and month[
                self.comboBox_month_PS.currentIndex()] == "Январь":
            table = 'Pokazanya_year_' + str(
                int(self.comboBox_year_PS.currentText()) - 1)

        read_table = sqlite3_read_db(self.data_base,
                                     table)  # читаем таблицу из базе данных
        read_table = read_table[0]

        for i in range(len(read_table)):
            pred_pokaz = read_table[i]  # показания сохраненного периода

            if self.label_month_year_PS.text() == pred_pokaz[1]:
                # присваеваем полям значения из сохраненной таблицы
                for a, b in zip(win_pole[:18], range(2, 19)):
                    a.setText(str(pred_pokaz[b]))
                break
            else:
                cor_month = month[self.comboBox_month_PS.currentIndex() - 1]
                if cor_month in pred_pokaz[1]:
                    # присваеваем полям "ПРЕДЫДУЩИЕ" значения из сохраненной таблицы
                    for c, d in zip(win_pole[:11:2], range(3, 14, 2)):
                        c.setText(str(pred_pokaz[d]))
                    # присваеваем полям "ПОСЛЕДНЕЕ" и "МЕСЯЧНЫЙ расход" значения "0"
                    for j in win_pole[1:12:2] + win_pole[12:17]:
                        j.setText("0")

        self.lineEdit_post_pokaz_P.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_P))
        self.lineEdit_pred_pokaz_P.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_P))
        self.lineEdit_post_pokaz_W1.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WC))
        self.lineEdit_pred_pokaz_W1.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WC))
        self.lineEdit_post_pokaz_W2.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WH))
        self.lineEdit_pred_pokaz_W2.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WH))
        self.lineEdit_post_pokaz_W3.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WC))
        self.lineEdit_pred_pokaz_W3.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WC))
        self.lineEdit_post_pokaz_W4.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WH))
        self.lineEdit_pred_pokaz_W4.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_WH))
        self.lineEdit_post_pokaz_G.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_G))
        self.lineEdit_pred_pokaz_G.textEdited[str].connect(
            lambda: self.text_editing(self.label_month_ras_G))
Exemple #18
0
def switchKeyboardLayoutTo(code):
    hex_id = list(_LAYOUTS.keys())[list(_LAYOUTS.values()).index(code)]
    win32api.LoadKeyboardLayout('00000' + hex_id.replace('0x', ''), 1)
Exemple #19
0
from tkinter import *
import win32api, random
import json
from win32api import GetSystemMetrics

VERSION = "0.4"

win32api.LoadKeyboardLayout("00000409", 1)

win_w = 434
win_h = 500

w_center_x = int((GetSystemMetrics(0) / 2) - (win_w / 2))
w_center_y = int((GetSystemMetrics(1) / 2) - (win_h / 2))

dbPath = "db/db.json"

baseFont = "Roboto"

# данные для шифрования паролей
KEY = 156
separator = {"dot": "[", "int_code": "]", "global_sep": "|"}

# список всех сервисов
services = {}
services_keys = []
serv_list = []

# данные для добавления и изменения сервисов
name_to_change = ''
name = ''