def test_get_string(self): # test invalid addresses cause a ValueError rather than crash! with pytest.raises(ValueError): win32gui.PyGetString(0) with pytest.raises(ValueError): win32gui.PyGetString(1) with pytest.raises(ValueError): win32gui.PyGetString(1, 1)
def UnpackLVITEM(buffer): item_mask, item_item, item_subItem, \ item_state, item_stateMask, \ item_textptr, item_cchText, item_image, \ item_param, item_indent = struct.unpack(_lvitem_fmt, buffer) # ensure only items listed by the mask are valid if not (item_mask & commctrl.LVIF_TEXT): item_textptr = item_cchText = None if not (item_mask & commctrl.LVIF_IMAGE): item_image = None if not (item_mask & commctrl.LVIF_PARAM): item_param = None if not (item_mask & commctrl.LVIF_INDENT): item_indent = None if not (item_mask & commctrl.LVIF_STATE): item_state = item_stateMask = None if item_textptr: text = win32gui.PyGetString(item_textptr) else: text = None return _MakeResult( "LVITEM item_item item_subItem item_state " "item_stateMask text item_image item_param item_indent", (item_item, item_subItem, item_state, item_stateMask, text, item_image, item_param, item_indent))
def UnpackTVITEM(buffer): item_mask, item_hItem, item_state, item_stateMask, \ item_textptr, item_cchText, item_image, item_selimage, \ item_cChildren, item_param = struct.unpack(_tvitem_fmt, buffer) # ensure only items listed by the mask are valid (except we assume the # handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a # mask that doesn't include the handle, but the docs explicity say it is.) if not (item_mask & commctrl.TVIF_TEXT): item_textptr = item_cchText = None if not (item_mask & commctrl.TVIF_CHILDREN): item_cChildren = None if not (item_mask & commctrl.TVIF_IMAGE): item_image = None if not (item_mask & commctrl.TVIF_PARAM): item_param = None if not (item_mask & commctrl.TVIF_SELECTEDIMAGE): item_selimage = None if not (item_mask & commctrl.TVIF_STATE): item_state = item_stateMask = None if item_textptr: text = win32gui.PyGetString(item_textptr) else: text = None return _MakeResult( "TVITEM item_hItem item_state item_stateMask " "text item_image item_selimage item_cChildren item_param", (item_hItem, item_state, item_stateMask, text, item_image, item_selimage, item_cChildren, item_param))
def _getMultipleWindowValues(hwnd, getCountMessage, getValueMessage): '''A common pattern in the Win32 API is that in order to retrieve a series of values, you use one message to get a count of available items, and another to retrieve them. This internal utility function performs the common processing for this pattern. Arguments: hwnd Window handle for the window for which items should be retrieved. getCountMessage Item count message. getValueMessage Value retrieval message. Returns: Retrieved items.''' result = [] BUFFER_SIZE = 256 buf = win32gui.PyMakeBuffer(BUFFER_SIZE) valuecount = win32gui.SendMessage(hwnd, getCountMessage, 0, 0) for itemIndex in range(valuecount): buf_len = win32gui.SendMessage(hwnd, getValueMessage, itemIndex, buf) result.append( win32gui.PyGetString( win32gui.PyGetBufferAddressAndLen(buf)[0], buf_len)) return result
def __get_text(self, hwnd): buf_size = 0 try: textlength = ctypes.c_long(0) hr = ctypes.windll.user32.SendMessageTimeoutA( hwnd, win32con.WM_GETTEXTLENGTH, 0, 0, 0, 200, ctypes.byref(textlength)) if hr == 0 or textlength.value < 0: return "" buf_size = textlength.value * 2 + 1 except win32gui.error: return "" if buf_size <= 0: return "" pybuffer = win32gui.PyMakeBuffer(buf_size) ret = win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, pybuffer) if ret: address, _ = win32gui.PyGetBufferAddressAndLen(pybuffer) text = win32gui.PyGetString(address, ret) return text return ""
def 窗口_取窗口文本内容(窗口句柄): bufSize = win32api.SendMessage(窗口句柄, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 strBuf = win32gui.PyMakeBuffer(bufSize) length = win32gui.SendMessage(窗口句柄, win32con.WM_GETTEXT, bufSize, strBuf) address, length = win32gui.PyGetBufferAddressAndLen(strBuf) text = win32gui.PyGetString(address, length) return text[:-1]
def UnpackMENUITEMINFO(s): (cb, fMask, fType, fState, wID, hSubMenu, hbmpChecked, hbmpUnchecked, dwItemData, lptext, cch, hbmpItem) = struct.unpack(_menuiteminfo_fmt, s) assert cb == len(s) if fMask & win32con.MIIM_FTYPE == 0: fType = None if fMask & win32con.MIIM_STATE == 0: fState = None if fMask & win32con.MIIM_ID == 0: wID = None if fMask & win32con.MIIM_SUBMENU == 0: hSubMenu = None if fMask & win32con.MIIM_CHECKMARKS == 0: hbmpChecked = hbmpUnchecked = None if fMask & win32con.MIIM_DATA == 0: dwItemData = None if fMask & win32con.MIIM_BITMAP == 0: hbmpItem = None if fMask & win32con.MIIM_STRING: text = win32gui.PyGetString(lptext, cch) else: text = None return _MakeResult( "MENUITEMINFO fType fState wID hSubMenu hbmpChecked " "hbmpUnchecked dwItemData text hbmpItem", (fType, fState, wID, hSubMenu, hbmpChecked, hbmpUnchecked, dwItemData, text, hbmpItem))
def UnpackDEV_BROADCAST(lparam): if lparam == 0: return None hdr_format = "iii" hdr_size = struct.calcsize(hdr_format) hdr_buf = win32gui.PyGetMemory(lparam, hdr_size) size, devtype, reserved = struct.unpack("iii", hdr_buf) # Due to x64 alignment issues, we need to use the full format string over # the entire buffer. ie, on x64: # calcsize('iiiP') != calcsize('iii')+calcsize('P') buf = win32gui.PyGetMemory(lparam, size) extra = x = {} if devtype == win32con.DBT_DEVTYP_HANDLE: # 2 handles, a GUID, a LONG and possibly an array following... fmt = hdr_format + "PP16sl" _, _, _, x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \ struct.unpack(fmt, buf[:struct.calcsize(fmt)]) x['eventguid'] = pywintypes.IID(guid_bytes, True) elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE: fmt = hdr_format + "16s" _, _, _, guid_bytes = struct.unpack(fmt, buf[:struct.calcsize(fmt)]) x['classguid'] = pywintypes.IID(guid_bytes, True) x['name'] = win32gui.PyGetString(lparam + struct.calcsize(fmt)) elif devtype == win32con.DBT_DEVTYP_VOLUME: # int mask and flags fmt = hdr_format + "II" _, _, _, x['unitmask'], x['flags'] = struct.unpack( fmt, buf[:struct.calcsize(fmt)]) else: raise NotImplementedError("unknown device type %d" % (devtype, )) return DEV_BROADCAST_INFO(devtype, **extra)
def UnpackLVCOLUMN(lparam): mask, fmt, cx, text_addr, text_size, subItem, image, order = struct.unpack( _lvcolumn_fmt, lparam ) # ensure only items listed by the mask are valid if not (mask & commctrl.LVCF_FMT): fmt = None if not (mask & commctrl.LVCF_WIDTH): cx = None if not (mask & commctrl.LVCF_TEXT): text_addr = text_size = None if not (mask & commctrl.LVCF_SUBITEM): subItem = None if not (mask & commctrl.LVCF_IMAGE): image = None if not (mask & commctrl.LVCF_ORDER): order = None if text_addr: text = win32gui.PyGetString(text_addr) else: text = None return _MakeResult( "LVCOLUMN fmt cx text subItem image order", (fmt, cx, text, subItem, image, order), )
def get_message(hwnd): buf_size = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH) + 1 # 要加上截尾的字节 str_buffer = win32gui.PyMakeBuffer(buf_size) # 生成buffer对象 win32api.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, str_buffer) # 获取buffer # str_buffer = str(str_buffer[:-1]) # 转为字符串 address, length = win32gui.PyGetBufferAddressAndLen(str_buffer) text = win32gui.PyGetString(address, length) return text
def __GetText(cls, hwnd): length = cls.__SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, None, None) + 1 buf = win32gui.PyMakeBuffer(length) cls.__SendMessage(hwnd, win32con.WM_GETTEXT, length, buf) address, length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, length - 1) return cls.__ConvertEncoding(text, False)
def get_dlg_txt(handle_): buf_size = win32gui.SendMessage(handle_, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 # 要加上截尾的字节 str_buffer = win32gui.PyMakeBuffer(buf_size) # 生成buffer对象 win32api.SendMessage(handle_, win32con.WM_GETTEXT, buf_size, str_buffer) # 获取buffer address, length = win32gui.PyGetBufferAddressAndLen(str_buffer) return win32gui.PyGetString(address, length)
def getcont(HW): length = win32gui.SendMessage(HW, win32con.WM_GETTEXTLENGTH) + 1 buf = win32gui.PyMakeBuffer(length) # 发送获取文本请求 win32api.SendMessage(HW, win32con.WM_GETTEXT, length, buf) # 下面应该是将内存读取文本 address, length = win32gui.PyGetBufferAddressAndLen(buf[:-1]) text = win32gui.PyGetString(address, length) return text
def 提取句柄文本(句柄): # 获取识别结果中输入框文本 length = win32gui.SendMessage(句柄, win32con.WM_GETTEXTLENGTH)+1 buf = win32gui.PyMakeBuffer(length) #发送获取文本请求 win32api.SendMessage(句柄, win32con.WM_GETTEXT, length, buf) #下面应该是将内存读取文本 address, length = win32gui.PyGetBufferAddressAndLen(buf[:-1]) text = win32gui.PyGetString(address, length) return text
def GetWinValue(h_win): length = win32gui .SendMessage(h_win, win32con.WM_GETTEXTLENGTH) + 1 # print('Length: ', length) buf = win32gui.PyMakeBuffer(length) win32gui .SendMessage(h_win, win32con.WM_GETTEXT, length, buf) address, result_length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, result_length) return text[:-1]
def getBufferContent(hwnd): buf_size = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) # print('buf_size: ', buf_size) buf = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf) # print('_buf_str: ', str(buf)) address, length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, length) buf.release() return text
def getText(hwnd): if hwnd == 0: return 'hwnd is not used return 0' length = 10000 buf = gui.PyMakeBuffer(length) length2 = gui.SendMessage(hwnd, con.WM_GETTEXT, length, buf) + 1 buf = gui.PyMakeBuffer(length2) gui.SendMessage(hwnd, con.WM_GETTEXT, length2, buf) address, length = gui.PyGetBufferAddressAndLen(buf) text = gui.PyGetString(address, length) return text
def GetTextData(hwnd, ID): #传入父句柄,控件ID hwnd = win32gui.GetDlgItem(hwnd, ID) buf_size = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 # 要加上截尾的字节 str_buffer = win32gui.PyMakeBuffer(buf_size) # 生成buffer对象 win32api.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, str_buffer) # 获取buffer address, length = win32gui.PyGetBufferAddressAndLen(str_buffer) text = win32gui.PyGetString(address, length - 1) return text
def Host(): try: TV = win32gui.FindWindow('#32770', 'TeamViewer') ID = win32gui.FindWindowEx(TV, 0, 'Edit', None) #print(hex(ID)) PW = win32gui.FindWindowEx(TV, ID, 'Edit', None) #print(hex(PW)) ID_buf_size = win32gui.SendMessage(ID, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 # 要加上截尾的字节 #print(buf_size) ID_str_buffer = win32gui.PyMakeBuffer( win32gui.SendMessage(ID, win32con.WM_GETTEXTLENGTH, 0, 0) + 1) # 生成buffer对象 #print(str_buffer) win32api.SendMessage(ID, win32con.WM_GETTEXT, ID_buf_size, ID_str_buffer) # 获取buffer ID_address, ID_length = win32gui.PyGetBufferAddressAndLen( ID_str_buffer) IDstr = win32gui.PyGetString(ID_address, ID_length) PW_buf_size = win32gui.SendMessage(PW, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 # 要加上截尾的字节 #print(buf_size) PW_str_buffer = win32gui.PyMakeBuffer( win32gui.SendMessage(PW, win32con.WM_GETTEXTLENGTH, 0, 0) + 1) # 生成buffer对象 #print(str_buffer) win32api.SendMessage(PW, win32con.WM_GETTEXT, PW_buf_size, PW_str_buffer) # 获取buffer PW_address, PW_length = win32gui.PyGetBufferAddressAndLen( PW_str_buffer) PWstr = win32gui.PyGetString(PW_address, PW_length) #异常代码验证 #Print (IDstr[:-1]+'\n'+PWstr[:-1]) return IDstr[:-1] + '\n' + PWstr[:-1] except Exception as e: return str(e)
def UnpackLVCOLUMN(lparam): format = "iiiiiiii" mask, fmt, cx, text_addr, text_size, subItem, image, order = \ struct.unpack(format, lparam) # ensure only items listed by the mask are valid if not (mask & commctrl.LVCF_FMT): fmt = None if not (mask & commctrl.LVCF_WIDTH): cx = None if not (mask & commctrl.LVCF_TEXT): text_addr = text_size = None if not (mask & commctrl.LVCF_SUBITEM): subItem = None if not (mask & commctrl.LVCF_IMAGE): image = None if not (mask & commctrl.LVCF_ORDER): order = None if text_addr: text = win32gui.PyGetString(text_addr) else: text = None return fmt, cx, text, subItem, image, order
def get_focus_window_text(): pos = win32api.GetCursorPos() print('GetCursorPos: ', pos) hWnd = win32gui.WindowFromPoint(pos) print('WindowFromPoint: ', hWnd) length = win32gui.SendMessage(hWnd, win32con.WM_GETTEXTLENGTH) + 1 print('Length: ', length) buf = win32gui.PyMakeBuffer(length) print('get: ', win32gui.SendMessage(hWnd, win32con.WM_GETTEXT, length, buf)) address, result_length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, result_length) print('text: ', text)
def get_window_text(hwnd): ''' 获取某窗口的窗口文本 :param hwnd: 待获取文本的窗口句柄 :return: 窗口文本,未获取到返回None ''' text = None if hwnd: # 文本框内容长度 length = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH) if length: length += 1 buf = win32gui.PyMakeBuffer(length) result_length = win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, length, buf) # print(result_length) address, length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, length) # print('text: ', text) return text
def callback(hwnd, window_hwnd): classname = win32gui.GetClassName(hwnd).lower() buffer_len = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 text = array('b', b'\x00\x00' * buffer_len) win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buffer_len, text) text = win32gui.PyGetString(text.buffer_info()[0], buffer_len - 1).lower() for match in self._windows[window_hwnd]['matches']: if match["text"] in text: self._windows[window_hwnd]['to_click'].append( match["button"]) if "button" in classname: self._windows[window_hwnd]['buttons'].append({ 'text': text, 'handle': hwnd, }) return True
def upload_file(path): result = False win32com.client.Dispatch("WScript.shell") second = 10 edit_text = 0 window_state = 0 while second > 0: window_state = win32gui.FindWindow(None, '打开') edit_text = win32gui.FindWindowEx(window_state, 0, 'ComboBoxEx32', None) if edit_text != 0: break time.sleep(1) second -= 1 if second == 0: print('超时1') timeout = 10 while timeout > 0: time.sleep(1) win32api.SendMessage(edit_text, win32con.WM_SETTEXT, 0, path) length = 4 buf = win32gui.PyMakeBuffer(length) win32api.SendMessage(edit_text, win32con.WM_GETTEXT, length, buf) address, length = win32gui.PyGetBufferAddressAndLen(buf) text = win32gui.PyGetString(address, length) timeout = timeout - 1 if text[0:2] == os.getcwd().split('\\')[0]: result = True break save_btn = win32gui.FindWindowEx(window_state, 0, 'Button', '打开(&O)') win32api.SendMessage(save_btn, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0) win32api.SendMessage(save_btn, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0) time.sleep(2) return result
def save_catalog_from_ss(ss): # os.startfile(qingtian_path) startAt = time.time() SW_MINIMIZE = 6 info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = SW_MINIMIZE subprocess.Popen(qingtian_path, startupinfo=info) # 这里启动也需要停一阵子(至少2秒) time.sleep(2) ori_ss = ss qingtian_hd = None while not qingtian_hd: qingtian_hd = win32gui.FindWindowEx(None, 0, 0, qingtian_name) feedSS_hd = get_hd_from_child_hds(qingtian_hd, 6, '') win32gui.SendMessage(feedSS_hd, win32con.WM_SETTEXT, 0, ss) print("gg") # 这里有爬虫,需要停一阵子(至少1秒)... time.sleep(1) # huoquzhong_hd=get_hd_from_child_hds(qingtian_hd,5,"获取") # cnt=0 # while cnt!=5: bookmark_hd = get_hd_from_child_hds(qingtian_hd, 1, '') # time.sleep(0.5) # cnt+=1 # time.sleep(0.5) # https: // blog.csdn.net / qq_41928442 / article / details / 88937337 # https://stackoverflow.com/questions/53182704/python-memorybuffer-pywin32 # 听人劝吃饱饭... # length = win32gui.SendMessage(bookmark_hd, win32con.WM_GETTEXTLENGTH)*2+2 # 我终于知道我错在哪里了 # https://blog.csdn.net/sinat_33384251/article/details/89444945 # 这里有3个length!!!赋值的时候一定不要弄错!!! length = win32gui.SendMessage(bookmark_hd, win32con.WM_GETTEXTLENGTH) length2 = length * 2 + 2 time.sleep(0.5) buf = win32gui.PyMakeBuffer(length2) #发送获取文本请求 win32api.SendMessage(bookmark_hd, win32con.WM_GETTEXT, length2, buf) time.sleep(1) #下面应该是将内存读取文本 address, length3 = win32gui.PyGetBufferAddressAndLen(buf[:-1]) # time.sleep(0.5) text = win32gui.PyGetString(address, length3)[:length] print(text) time.sleep(0.5) error_line = "没有查询到此SS的书签!" if error_line in text: ss = "error_" + ss try: with open(target_dir + os.sep + ss + ".txt", "w", encoding="utf-8") as f: f.write(text) with open(target_dir + os.sep + "already_save.txt", "a", encoding="utf-8") as f: f.write(ori_ss + "\n") except Exception: print(f"{ss} 无法写入!") pass win32gui.PostMessage(qingtian_hd, win32con.WM_CLOSE, 0, 0) time.sleep(0.5) endAt = time.time() run_time = endAt - startAt print(f"{ss} Run time:{run_time}")
def getFilename(self): return win32gui.PyGetString(self.fn_buf_addr)
# 获取窗口文本不含截尾空字符的长度 # 参数:窗口句柄; 消息类型; 参数WParam; 参数IParam bufSize = win32api.SendMessage(subHandle, win32con.WM_GETTEXTLENGTH, 0, 0) +1 # 利用api生成Buffer strBuf = win32gui.PyMakeBuffer(bufSize) print(strBuf) # 发送消息获取文本内容 # 参数:窗口句柄; 消息类型;文本大小; 存储位置 length = win32gui.SendMessage(subHandle, win32con.WM_GETTEXT, bufSize, strBuf) # 反向内容,转为字符串 # text = str(strBuf[:-1]) address, length = win32gui.PyGetBufferAddressAndLen(strBuf) text = win32gui.PyGetString(address, length) # print('text: ', text) # 鼠标单击事件 #鼠标定位到(30,50) win32api.SetCursorPos([30,150]) #执行左单键击,若需要双击则延时几毫秒再点击一次即可 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) #右键单击 win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP | win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) def click1(x,y): #第一种 win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
def save_catalog_from_ss(ss, target_dir2=target_dir, filename=None, error_dir=None): # startAt=time.time() # os.startfile(qingtian_path) startAt = time.time() SW_MINIMIZE = 6 info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = SW_MINIMIZE subprocess.Popen(qingtian_path, startupinfo=info) # SW_MINIMIZE = 6 # info = subprocess.STARTUPINFO() # info.dwFlags = subprocess.STARTF_USESHOWWINDOW # info.wShowWindow = SW_MINIMIZE # subprocess.Popen(qingtian_path, startupinfo=info) # 这里启动也需要停一阵子(至少2秒) time.sleep(2) ori_ss = ss qingtian_hd = None while not qingtian_hd: qingtian_hd = win32gui.FindWindowEx(None, 0, 0, qingtian_name) feedSS_hd = get_hd_from_child_hds(qingtian_hd, 6, '') win32gui.SendMessage(feedSS_hd, win32con.WM_SETTEXT, 0, ss) time.sleep(2) print("gg") # 这里有爬虫,需要停一阵子(至少1秒)... # time.sleep(2) # huoquzhong_hd=get_hd_from_child_hds(qingtian_hd,5,"获取") # cnt=0 # while cnt!=5: # bookmark_pos=(755, 378) # click_on_pos(bookmark_pos) # # 全选操作 # win32api.keybd_event(17,0,0,0) #ctrl键位码是17 # win32api.keybd_event(65,0,0,0) #A键位码是65 # win32api.keybd_event(65,0,win32con.KEYEVENTF_KEYUP,0) #释放按键 # win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0) # # 复制操作 # win32api.keybd_event(17,0,0,0) #ctrl键位码是17 # win32api.keybd_event(67,0,0,0) #C键位码是67 # win32api.keybd_event(67,0,win32con.KEYEVENTF_KEYUP,0) #释放按键 # win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0) # time.sleep(1) # text = getText() # 得到剪切板上的数据 # # byte_str_charset = chardet.detect(byte_str) # 获取字节码编码格式 # # print(byte_str_charset) # # byte_str = str(byte_str, byte_str_charset.get('encoding')) # 将八进制字节转化为字符串 bookmark_hd = get_hd_from_child_hds(qingtian_hd, 1, '') # 我终于知道我错在哪里了 # https://blog.csdn.net/sinat_33384251/article/details/89444945 # 这里有3个length!!!赋值的时候一定不要弄错!!! length = win32gui.SendMessage(bookmark_hd, win32con.WM_GETTEXTLENGTH) length2 = length * 2 + 2 time.sleep(0.5) buf = win32gui.PyMakeBuffer(length2) #发送获取文本请求 win32api.SendMessage(bookmark_hd, win32con.WM_GETTEXT, length2, buf) time.sleep(1) #下面应该是将内存读取文本 address, length3 = win32gui.PyGetBufferAddressAndLen(buf[:-1]) # time.sleep(0.5) text = win32gui.PyGetString(address, length3)[:length] print(text) error_line = "没有查询到此SS的书签!" # try: # print("Text:\t",text) # except UnicodeEncodeError: # print("Text:\t",bad_filename(text)) # print("Text type:\t",type(text)) print("Text len:", len(text)) if error_line in text: ss = "error_" + ss try: with open(target_dir2 + os.sep + ss + ".txt", "w", encoding="utf-8") as f: if len(text) <= 10: raise Exception f.write(text) if filename != None: assert not filename.endswith(".pdf") os.rename( target_dir2 + os.sep + ss + ".txt", target_dir2 + os.sep + ss + "ssidssid" + filename + ".txt") with open(target_dir2 + os.sep + "already_save.txt", "a", encoding="utf-8") as f: f.write(ori_ss + "\n") except Exception: if os.path.exists(target_dir2 + os.sep + ss + ".txt"): os.remove(target_dir2 + os.sep + ss + ".txt") if error_dir != None: if not os.path.exists(error_dir): os.makedirs(error_dir) with open(f"{error_dir}{os.sep}fetch-errors.txt", "a", encoding="utf-8") as f: f.write(ss + "\t\t\t" + filename + "\n") print(f"{ss} 无法写入!") pass win32gui.PostMessage(qingtian_hd, win32con.WM_CLOSE, 0, 0) # 防止写到另一个框框里的文件... time.sleep(3) endAt = time.time() run_time = endAt - startAt print(f"{ss} Run time:{run_time}")
def check_type(pdf_path, pdf_name, pdf_dir=target_dir): # pdf_path="D:\\AllDowns\\gpgp.pdf" # pdf_name="gpgp.pdf" # # os.chdir(pdf_dir) # pdf_name=os.path.abspath(pdf_name) # # avDoc=win32com.client.DispatchEx("AcroExch.AVDoc") # ret = avDoc.Open(f"\"{pdf_path}\"",f"\"{pdf_path}\"") # # time.sleep(5) # 用com去控制老是有问题,只能改成默认设置妈的! # adobe_comm=f"D:\\Acrobat 11.0\\Acrobat\\AcroRd32.exe /n \"{pdf_path}\"" # # print(adobe_comm) # os.system(adobe_comm) # 用com去控制老是有问题,唉... # nmd,每次运行之前都要查看一下用的是哪款pdf阅读器就离谱... # 2020年9月26日01:57:50,重启试了下发现还是gg。算了算了.. os.startfile(pdf_path) time.sleep(2) root_hd = None # 防止“打开文档时发生错误”什么的 adobe_str = "Adobe Acrobat" adobe_hd = win32gui.FindWindowEx(root_hd, 0, 0, adobe_str) if adobe_hd: queding_hd = get_hd_from_child_hds(adobe_hd, 5, "") win32gui.SendMessage(queding_hd, win32con.BM_CLICK) # adobe_str=f"{pdf_name} - Adobe Acrobat Pro" adobe_str = "Adobe Acrobat Pro" adobe_hd = get_hd_from_child_hds(root_hd, None, adobe_str) if not adobe_hd: press_alt_f4() return 0 avui_CommandWidget_hd = get_hd_from_child_hds( adobe_hd, 0, expect_name="AVUICommandWidget") # 固定是第二个... state_hd = get_hd_from_child_hds(avui_CommandWidget_hd, 1, expect_name="") # https://blog.csdn.net/qq_41928442/article/details/88937337 # 获取识别结果中输入框文本 length = win32gui.SendMessage(state_hd, win32con.WM_GETTEXTLENGTH) + 1 buf = win32gui.PyMakeBuffer(length) #发送获取文本请求 win32api.SendMessage(state_hd, win32con.WM_GETTEXT, length, buf) #下面应该是将内存读取文本 address, length = win32gui.PyGetBufferAddressAndLen(buf[:-1]) text = win32gui.PyGetString(address, length) flag = 0 print(f"Text:{text}") if text == "1": print("Type 1") flag = 1 elif text == "A": print("Type 2") flag = 2 win32gui.PostMessage(adobe_hd, win32con.WM_CLOSE, 0, 0) print("one done.") # avDoc.Close(True) # # del avDoc time.sleep(3) return flag
def save_catalog_from_ss(ss,target_dir2=target_dir,filename=None,error_dir=None): startAt=time.time() # os.startfile(qingtian_path) SW_MINIMIZE = 6 info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = SW_MINIMIZE subprocess.Popen(qingtian_path, startupinfo=info) # 这里启动也需要停一阵子(至少2秒) time.sleep(2) ori_ss=ss qingtian_hd=win32gui.FindWindowEx(None,0,0,qingtian_name) feedSS_hd=get_hd_from_child_hds(qingtian_hd,6,'') win32gui.SendMessage(feedSS_hd,win32con.WM_SETTEXT,0,ss) time.sleep(5) print("gg") # 这里有爬虫,需要停一阵子(至少1秒)... time.sleep(1) # huoquzhong_hd=get_hd_from_child_hds(qingtian_hd,5,"获取") # cnt=0 # while cnt!=5: bookmark_hd=get_hd_from_child_hds(qingtian_hd,1,'') # time.sleep(0.5) # cnt+=1 # time.sleep(0.5) # https: // blog.csdn.net / qq_41928442 / article / details / 88937337 # https://stackoverflow.com/questions/53182704/python-memorybuffer-pywin32 # 听人劝吃饱饭... # length = win32gui.SendMessage(bookmark_hd, win32con.WM_GETTEXTLENGTH)*2+2 length = win32gui.SendMessage(bookmark_hd, win32con.WM_GETTEXTLENGTH,0,0)*2+2 time.sleep(1) buf = win32gui.PyMakeBuffer(length) #发送获取文本请求 win32api.SendMessage(bookmark_hd, win32con.WM_GETTEXT, length, buf) #下面应该是将内存读取文本 time.sleep(1) # text=buf[:length] address, length = win32gui.PyGetBufferAddressAndLen(buf[:-1]) time.sleep(1) text = win32gui.PyGetString(address, length) time.sleep(1) error_line="没有查询到此SS的书签!" # try: # print("Text:\t",text) # except UnicodeEncodeError: # print("Text:\t",bad_filename(text)) # print("Text type:\t",type(text)) print("Text len:",len(text)) if error_line in text: ss="error_"+ss try: with open(target_dir2+os.sep+ss+".txt","w",encoding="utf-8") as f: if len(text)<=10: raise Exception f.write(text) if filename!=None: assert not filename.endswith(".pdf") os.rename(target_dir2+os.sep+ss+".txt",target_dir2+os.sep+ss+"ssidssid"+filename+".txt") with open(target_dir2+os.sep+"already_save.txt","a",encoding="utf-8") as f: f.write(ori_ss+"\n") except Exception: if os.path.exists(target_dir2+os.sep+ss+".txt"): os.remove(target_dir2+os.sep+ss+".txt") if error_dir!=None: if not os.path.exists(error_dir): os.makedirs(error_dir) with open(f"{error_dir}{os.sep}fetch-errors.txt","a",encoding="utf-8") as f: f.write(ss+"\t\t\t"+filename+"\n") print(f"{ss} 无法写入!") pass win32gui.PostMessage(qingtian_hd,win32con.WM_CLOSE,0,0) time.sleep(1) endAt=time.time() run_time=endAt-startAt print(f"{ss} Run time:{run_time}")