用pywin写简单的窗口界面

工作的关系,要截取一窗口的屏幕内容,然后保存到一个EXCEL文件中。我是个比较懒惰的人,就写了个Python程序完成这一连串工作。(计算机就是要干苦活累活嘛,所以有人说,程序员的懒惰是一种美德,很是赞同!)

#!coding = utf-8
import win32ui
import win32gui
import win32con
from pywin.mfc import dialog

import os
import string

from pyExcelerator import *
from PIL import ImageGrab

#====Constant Definations=======================================
IDC_COMBOBOX_1 = 2034
IDC_COMBOBOX_2 = 2035
IDC_COMBOBOX_3 = 2036
IDC_COMBOBOX_4 = 2037

BMP_FILE_NAME = "case.bmp"
CURRENT_DIR = "C:¥¥Documents and Settings¥¥zhoukai¥¥Desktop¥¥CASE_DIR¥¥"
OPEN_TOOL = "mspaint"
BMP_FILE = CURRENT_DIR + BMP_FILE_NAME
CASE_DIR = CURRENT_DIR + "CASE_DIR¥¥"
EXCEL_PATH = "excel"
WINDOW_NAME = r"TEST Window- Microsoft Internet Explorer"
WINDOW_NAME_CASE = r"TEST Window2- Microsoft Internet Explorer"
#================================================================

#===Get the screen and save it ==========================================
def save_window(window_name):
    try:
        #Test code
        #win = win32ui.GetForegroundWindow()
        #str1 = win.GetWindowText()

        #获取指定的窗口handle
        handle = win32ui.FindWindow(None,window_name)
        #使之指定窗口为前景窗口
        preActiveWnd = handle.SetForegroundWindow()   
        #取得指定窗口的Window大小
        rangle = handle.GetWindowRect()   
        #print rangle
        #这里用time.sleep是用于测试的:-)
        import time
        time.sleep(0.5)
        "使用PIL的ImageGrab.grab取得屏幕内容(注:这个函数只能用于Win)
        im = ImageGrab.grab(rangle)
        "保存截屏
        im.save( BMP_FILE ) # or call im.show() to view the image directly
   "简单的Exception handle
    except:
        win32ui.MessageBox("SAVE_Window ERROR",¥
                'ERROR‾‾‾!"'+WINDOW_NAME + '"is not existe.', ¥
                win32con.MB_OK)
               
#===Create Excel File===================================================
"创建EXCEL文件
def create_excel( xls_file, sheet_name ):
    if( sheet_name == None or sheet_name == "" ):
        sheet_name = "001"
    w = Workbook()
    ws = w.add_sheet( sheet_name )
    ws.insert_bitmap( BMP_FILE, 2, 2)
    w.save( xls_file )
    #print xls_file
    #os.startfile(xls_file)

#=====GUI PART===========================================================
'''晕倒,总算到重点了。
'''pywin中封装了MFC。就可以用MFC那样写Win的窗口了。
'''首先创建窗口模板。就是在VC中RC文件中的窗口元素定义。
'''简单的方法就是用VC IDE编辑好窗口样式后,copy过来用了。
'''我是记不住那么多的窗口样式定义的。呵呵……
def MakeLoginDlgTemplate(title):
    style = win32con.DS_MODALFRAME | win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT
    cs = win32con.WS_CHILD | win32con.WS_VISIBLE
    cs2= win32con.CBS_DROPDOWN | win32con.WS_VSCROLL | win32con.WS_TABSTOP

    # Window frame and title
    dlg = [ [title, (0, 0, 343, 90), style, None, (10, "MS ゴシック")], ]

    dlg.append([130, "CASE NAME:", -1, (7, 9, 69, 9), cs | win32con.SS_LEFT])
    s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
    dlg.append(['COMBOBOX',None, IDC_COMBOBOX_1, (50, 7, 243,60), s| cs2|cs])

    dlg.append([130, "CASE NO:", -1, (7, 22, 69, 9), cs | win32con.SS_LEFT])
    s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
    dlg.append(['COMBOBOX', None, IDC_COMBOBOX_2, (50, 20, 243,50), s | cs2|cs])

    # Password label and text box
    # 130就是Static Text的ID。我当时郁闷了好久,这128,130是干什么的呀?
    # 后来才知道,128是Button.130是static text(lable). #@!!~~~
    dlg.append([130, "CASE TYPE:", -1, (7, 33, 69, 9), cs | win32con.SS_LEFT])
    s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
    dlg.append(['COMBOBOX', None, IDC_COMBOBOX_3, (50, 33, 243,63), s | cs2|cs])
    #Window Name lable and text box
    dlg.append([130, "Window NAME:", -1, (7, 46, 69, 9), cs | win32con.SS_LEFT])
    s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
    dlg.append(['COMBOBOX',None, IDC_COMBOBOX_4, (50, 46, 243,76), s| cs2|cs])

    # OK/Cancel Buttons
    s = cs | win32con.WS_TABSTOP
    dlg.append([128, "OK", win32con.IDOK, (295, 5, 40, 14), s | win32con.BS_DEFPUSHBUTTON])
    s = win32con.BS_PUSHBUTTON | s
    dlg.append([128, "Kill", win32con.IDCANCEL, (295, 20, 40, 14), s])
    return dlg

"定义一个窗口类,继承于Dialog类
class SelectDlg(dialog.Dialog):
    def __init__(self, title):
        dialog.Dialog.__init__(self, MakeLoginDlgTemplate(title) )
        self.case_name = ""
        self.case_no = ""
        self.case_type =""
        self.file_name = ""
        self.window_name = ""
   
    def OnInitDialog (self):
        rc = dialog.Dialog.OnInitDialog (self)
       #分别初始化窗口元素。
        self.combol1 = self.GetDlgItem(IDC_COMBOBOX_1)
        self.combol1.AddString("CASE 01")
        self.combol1.AddString("CASE 02")
        self.combol1.AddString("CASE 02")

        self.combol2 = self.GetDlgItem(IDC_COMBOBOX_2)
        for i in range(1,40):
            self.combol2.InsertString( i-1,"(CASE_" + string.zfill(str(i),3) + ")")

        self.combol3 = self.GetDlgItem(IDC_COMBOBOX_3)
        self.combol3.InsertString(0,'_Input')
        self.combol3.InsertString(1,'_Output')

        self.combol4 = self.GetDlgItem(IDC_COMBOBOX_4)
        self.combol4.InsertString(0,'WINDOW NAME')
        self.combol4.InsertString(1,'WINDOW NAME2')
        self.combol4.SetCurSel(0)
   
        #print self.combol1.GetCount()
        return rc
   
    #OK Button 的处理函数
    def OnOK(self):
        if( not os.path.exists(CASE_DIR ) ):
            os.mkdir( CASE_DIR )
        win_name, s_name, xsl_file = self.get_case_info()
        print win_name, s_name, xsl_file
        save_window(win_name)
        #print s_name, xsl_file
        if os.path.exists( xsl_file):
            if (win32con.IDYES == win32ui.MessageBox("Comfirm", ¥
                                                     'File: "' + xsl_file +'existe, Overwrite it!',¥
                                                     win32con.MB_YESNO|win32con.MB_ICONWARNING)):
                create_excel( unicode(xsl_file,'cp932'), s_name )
        else:
            create_excel( unicode(xsl_file,'cp932'), s_name )
        dialog.Dialog.OnOK(self)

    #这是个辅助函数,取得窗口输入,生成所要的字符串
    def get_case_info(self):
        self.case_name = self.combol1.GetWindowText();
        self.case_no = self.combol2.GetWindowText()
        self.case_type = self.combol3.GetWindowText()
        self.window_name = self.combol4.GetWindowText()
        sheet_name = unicode( self.case_name + self.case_no,'cp932' )
        excel_name = CASE_DIR + self.case_name + self.case_no + self.case_type + '.xls'
        #excel_name = unicode( excel_name,'cp932')
        return ( self.window_name, sheet_name, excel_name )

#========================================================================


if __name__ == "__main__":
   dlg = SelectDlg("")
   #dlg.CreateWindow();
   #这里要说明下。由于我使用的是pythonw来执行这个脚本,不能用
   #CreateWindow()来创建窗口,因为CreateWindow()调用后,python
    #隐藏的主进程就会继续执行下去,在你还没有看到窗口显示的时候,窗口
   #也就随着隐藏的主进程运行完毕而结束了。所以,可以用DoModal()
   #  来使得进程处于等待状态。(ps:我说的都晕了,其实试一试就知道了)
   dlg.DoModal()

posted on 2008-10-22 13:47  starspace  阅读(1116)  评论(0编辑  收藏  举报

导航