Python win32gui 实现自动文档另存为功能

该博客介绍了如何通过Python的win32api和win32gui库模拟键盘和鼠标操作,将RTF文档转换成TXT文档。代码中定义了几个类,包括KeyBoardOperation、MouseOperation和SaveAsFileWithOtherType,这些类组合起来实现了打开RTF文件,选择另存为,设置保存路径和文件类型,最后确认保存的操作流程。
摘要由CSDN通过智能技术生成

需要把rft文档转换成txt文档,尝试了各种方法,最后用win32gui,win32api配合完成,代码如下

import win32api,win32gui,win32con
import time

class KeyBoardOperation(object):
    def __init__(self,address):
        self.address_str=address

    KeyBoardCode=\
        {"a": 65, "b": 66, "c": 67, "d": 68, "e": 69, "f": 70, "g": 71, "h": 72, "i": 73, "j": 74, "k": 75, "l": 76, "m": 77,
         "n": 78, "o": 79, "p": 80, "q": 81, "r": 82, "s": 83, "t": 84, "u": 85, "v": 86, "w": 87, "x": 88, "y": 89, "z": 90,
         "A": 65, "B": 66, "C": 67, "D": 68, "E": 69, "F": 70, "G": 71, "H": 72, "I": 73, "J": 74, "K": 75, "L": 76, "M": 77,
         "N": 78, "O": 79, "P": 80, "Q": 81, "R": 82, "S": 83, "T": 84, "U": 85, "V": 86, "W": 87, "X": 88, "Y": 89, "Z": 90,
         "0": 48, "1": 49, "2": 50, "3": 51, "4": 52, "5": 53, "6": 54, "7": 55, "8": 56, "9": 57,
        "\\":220,".":190,":":[16,186]," ":8
        }
    def select_new_address(self):
        for key_str in self.address_str:
            time.sleep(1)
            if isinstance(self.KeyBoardCode[key_str],list):
                for key in self.KeyBoardCode[key_str]:
                    win32api.keybd_event(key, 0, 0, 0)  #
                for key in self.KeyBoardCode[key_str]:
                    win32api.keybd_event(key, 0, win32con.KEYEVENTF_KEYUP, 0)
            else:
                win32api.keybd_event(self.KeyBoardCode[key_str], 0, 0, 0)  #
                win32api.keybd_event(self.KeyBoardCode[key_str], 0, win32con.KEYEVENTF_KEYUP, 0)
        win32api.keybd_event(13, 0, 0, 0)  # a
        win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)

class MouseOperation(object):
    def __init__(self):
        pass

    def mouse_click(self,x, y):
        win32api.SetCursorPos([x, y])
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

    def button_click(self,handle,delay):
        time.sleep(delay)
        x_l, y_u, x_r, y_d= win32gui.GetWindowRect(handle)
        x=int(x_l+(x_r-x_l)/2)
        y=int(y_u+(y_d-y_u)/2)
        self.mouse_click(x, y)
        time.sleep(delay)

class SaveAsFileWithOtherType(MouseOperation,KeyBoardOperation):
    def __init__(self,app, filename,address):
        self.address_str=address
        win32api.ShellExecute(0, 'open', app, filename, "", 1);
        time.sleep(2)

    def find_window(self,titlename,calssname=None):
        win = win32gui.FindWindow(calssname, titlename)
        if not win:
            loop=60
            while loop:
                win = win32gui.FindWindow(calssname, titlename)
                time.sleep(1)
                if win:#find the window
                    break
                loop-=1
            else:
                print("The window is not opened in one minute!")
        return win

    def open_save_dialog_box(self,titlename,classname=None):
        self.win = self.find_window(titlename, classname)
        if self.win:
            win32api.keybd_event(18, 0, 0, 0)  # alt
            win32api.keybd_event(70, 0, 0, 0)  # f
            win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(70, 0, win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(65, 0, 0, 0)  # a
            win32api.keybd_event(65, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(3)
        else:
            print("No %s window found!"%titlename)

    def save_as_setting(self,titlename,classname=None):
        save_as_win=self.find_window(titlename,classname)
        if save_as_win:
            a1 = win32gui.FindWindowEx(save_as_win, None, "DUIViewWndClassName", None)
            a2 = win32gui.FindWindowEx(a1, None, "DirectUIHWND", None)
            a3 = win32gui.FindWindowEx(a2, None, "FloatNotifySink", None)
            # find file name dialog box
            a4 = win32gui.FindWindowEx(a3, None, "ComboBox", None)  # filename
            # Input filename
            time.sleep(1)
            hwnd_filename = win32gui.FindWindowEx(a4, None, "Edit", None)
            win32gui.SendMessage(hwnd_filename, win32con.WM_SETTEXT, None, "test.txt")

            # file file type dialog box
            a5 = win32gui.FindWindowEx(a2, a3, "FloatNotifySink", None)
            a6 = win32gui.FindWindowEx(a2, a5, "FloatNotifySink", None)
            hwnd_filetype = win32gui.FindWindowEx(a6, None, "ComboBox", None)  # file type
            # 直接操作 combobox,select file type
            item_index = 3  # 索引值是从0开始的,这里是第3项
            win32api.SendMessage(hwnd_filetype, win32con.CB_SETCURSEL, item_index, 0)
            win32api.SendMessage(self.win, hwnd_filetype, win32con.WM_COMMAND, 0)

            # find address dialog box
            a1 = win32gui.FindWindowEx(save_as_win, None, "WorkerW", None)
            a2 = win32gui.FindWindowEx(a1, None, "ReBarWindow32", None)
            a3 = win32gui.FindWindowEx(a2, None, "Address Band Root", None)
            a4 = win32gui.FindWindowEx(a3, None, "msctls_progress32", None)
            a5 = win32gui.FindWindowEx(a4, None, "Breadcrumb Parent", None)
            hwnd_filepath1 = win32gui.FindWindowEx(a5, None, "ToolbarWindow32", None)

            win32gui.PostMessage(hwnd_filepath1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0)  # enter
            win32gui.PostMessage(hwnd_filepath1, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0)
            # time.sleep(3)
            self.select_new_address()

            a1 = win32gui.FindWindowEx(save_as_win, None, "Button", None)
            save_button = win32gui.FindWindowEx(save_as_win, a1, "Button", None)
            self.button_click(save_button, 1)

    def save_confirm(self):
        #the file has existed,comfirm and replace it
        calssname = u"#32770"
        titlename = u"确认另存为"
        comfir_b=win32gui.FindWindow(calssname,titlename)
        if comfir_b:
            win32gui.SetForegroundWindow(comfir_b)
            a1 = win32gui.FindWindowEx(comfir_b,None,"DirectUIHWND",None)
            a2 = win32gui.FindWindowEx(a1, None, "CtrlNotifySink", None)
            for i in range(6):
                a2 = win32gui.FindWindowEx(a1, a2, "CtrlNotifySink", None)
            Y_Button = win32gui.FindWindowEx(a2, None, "Button", None)
            self.button_click(Y_Button, 1)
        # else:
        #     print "The file is not existed!"

        # confirm file format
        calssname = u"#32770"
        titlename = u"写字板"
        comfir_b = win32gui.FindWindow(calssname, titlename)
        if comfir_b:
            a1 = win32gui.FindWindowEx(comfir_b, None, "Button", None)
            self.button_click(a1, 1)
        # else:
        #     print "TEST"

    def close(self):
        # 关闭窗口
        win32gui.PostMessage(self.win, win32con.WM_CLOSE, 0, 0)

def main():
    filename=r"C:\Users\yangjjin\Desktop\test.rtf"
    new_addess=r"C:\Users\yangjjin"

    if filename.find("\\"):
        filename.replace("\\","\\\\")
        filename="\""+filename+"\""
    else:
        print("Please check filename!")

    ob=SaveAsFileWithOtherType("wordpad.exe",filename,new_addess)
    try:
        ob.open_save_dialog_box(u'test.rtf - 写字板')
        calssname = u"#32770"
        titlename = u"保存为"
        ob.save_as_setting(titlename,calssname)
        ob.save_confirm()
    finally:
        pass
        ob.close()



if __name__ == '__main__':
    main()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值