# -*- coding: utf-8 -*- GlobalPVersion='0.9.130' import sys,os,os.path,time,ctypes,types,re,datetime import struct, array #import mmap #import msvcrt global DEBUGFLAG DEBUGFLAG=False try: import winxpgui as win32gui except: import win32gui print "pb XP" #import win32gui import win32api, win32con, win32file import winerror, commctrl import win32gui_struct import win32com,win32com.client,win32process import threading,cPickle import win32ui def pywin32_version(): for path in sys.path: if os.path.isdir(path): filename = os.path.join(path, 'pywin32.version.txt') if os.path.isfile(filename): with open(filename) as f: pywin32_version = f.read() pywin32_version = pywin32_version.strip() return int(pywin32_version) global_pywin32_version=pywin32_version() """ dd=time.time() import subprocess from multiprocessing import Process try: import PIL,PIL.Image,PIL.ImageWin import Image except: pass try: from scintillacon import * except: pass df=time.time() print df-dd """ # --- Formats ---------------------------------------------------------------- format_string=0 format_repr=1 format_utf8=2 format_majssaccent=3 format_date=11 # jj.mm.aa format_datetime=12 format_dateouheurejour=13 #heure si aujourd'hui, sinon date format_datetime4=14 #JJ.MM.AA HH:MM (comme 12 mais 4 espaces) format_datetime4time=15 #JJ.MM.AA HH:MM (comme 12 mais 4 espaces) format_dateouheurejourhhmm=16 #comme 13 sauf "sinon date/heure" format_datetime4time=17 #comme 14, pour time.time() format_date4=19 # jj.mm.aaaa format_s_date=20 # enregistre comme chaine sous forme aaaa.mm.jj format_int=31 format_float=41 pywig_format={} pywig_format[0]="format_string" pywig_format[1]="format_repr" pywig_format[2]="format_utf8" pywig_format[3]="format_majssaccent" pywig_format[11]="format_date" pywig_format[12]="format_datetime" pywig_format[13]="format_dateouheurejour" pywig_format[14]="format_datetime4" pywig_format[15]="format_datetime4time" pywig_format[16]="format_dateouheurejourhhmm" pywig_format[17]="format_datetime4time" pywig_format[19]="format_date4" pywig_format[31]="format_int" pywig_format[41]="format_float" # ---------------------------------------------------------------------------- global_TEST=False signal_invisible=-444 plance_info = win32process.STARTUPINFO() # voir http://docs.activestate.com/activepython/2.4/pywin32/PySTARTUPINFO.html plance_info.dwFlags=1 plance_info.wShowWindow=2 """ plance_info=subprocess.STARTUPINFO() plance_info.dwFlags=1 plance_info.wShowWindow=2 """ """ print print "win32con" for i in dir(win32con): if i.find("SCROLL")>-1: print i #,eval("Title."+i) sys.exit() """ """ WM_PSD_PAGESETUPDLG 1024 WM_CUT 768 """ #(LVM_FIRST + 177) def defautpil(): global PIL try: test=PIL except: try: import PIL,PIL.Image,PIL.ImageWin import Image except: pass win32gui.InitCommonControlsEx(256) # 256 = ICC_DATE_CLASSES = 0x00000100 global wtop,wtopctrl,kprec,ktime,kprecnb,pwg_hotkey,globalkeyflag globalkeyflag=False global dernierecommand,derniereparam dernierecommand=None derniereparam=None wtop=None wtopctrl=None pwg_hotkey=None ktime=time.time() kprec = -999 kprecnb = 0 #pdebug=False pdebug=True pfdir32=os.path.expandvars("%ProgramFiles(x86)%") #print "PF_dir_32:",pfdir32 if pfdir32 == "%ProgramFiles(x86)%": pfdir32=os.path.expandvars("%ProgramFiles%") #print "PF_dir_32:",pfdir32 def u1252(chu): try: if type(chu) is unicode: return chu.encode('cp1252','replace') else: return chu except: return repr(chu) def uutf8(chu): try: if type(chu) is unicode: return chu.encode('utf-8','replace') else: return chu except: try: return repr(chu).encode('utf-8','replace') except: return repr(chu) def utf8inansi(ch=''): if ch=='': ch=GlobalPARAM[0].encode('cp1252','replace') chaineretour=ch.decode('cp1252').encode('utf-8') return chaineretour def utf81252(ch=''): #chaineretour=ch.decode('utf-8','ignore').encode('cp1252','replace') chaineretour=ch.encode('cp1252','replace') return chaineretour def d1252(ch=''): #chaineretour=ch.decode('utf-8','ignore').encode('cp1252','replace') return unicode(ch,'cp1252','replace') def utf8fromansi(ch=''): if ch=='': ch=GlobalPARAM[0] chaineretour=ch.decode('utf-8') return chaineretour def sfill(valeur,largeur,fill="0"): s= fill*(largeur-len(valeur)) return s+valeur mappingcharnumber = { chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'.', chr(45):'.', chr(46):'.', chr(47):'.', chr(48):'0', chr(49):'1', chr(50):'2', chr(51):'3', chr(52):'4', chr(53):'5', chr(54):'6', chr(55):'7', chr(56):'8', chr(57):'9', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(65):'', chr(66):'', chr(67):'', chr(68):'', chr(69):'', chr(70):'', chr(71):'', chr(72):'', chr(73):'1', chr(74):'', chr(75):'', chr(76):'', chr(77):'', chr(78):'', chr(79):'0', chr(80):'', chr(81):'', chr(82):'', chr(83):'', chr(84):'', chr(85):'', chr(86):'', chr(87):'', chr(88):'', chr(89):'', chr(90):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'', chr(98):'', chr(99):'', chr(100):'', chr(101):'', chr(102):'', chr(103):'', chr(104):'', chr(105):'1', chr(106):'', chr(107):'', chr(108):'1', chr(109):'', chr(110):'', chr(111):'0', chr(112):'', chr(113):'', chr(114):'', chr(115):'', chr(116):'', chr(117):'', chr(118):'', chr(119):'', chr(120):'', chr(121):'', chr(122):'', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'', chr(129):'', chr(130):'', chr(131):'', chr(132):'', chr(133):'', chr(134):'', chr(135):'.', chr(137):'', chr(138):'', chr(139):'', chr(140):'0', chr(141):'', chr(142):'', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'.', chr(151):'', chr(152):'.', chr(153):'.', chr(154):'', chr(155):'', chr(156):'0', chr(157):'', chr(158):'', chr(159):'', chr(160):'', chr(161):'1', chr(162):'', chr(163):'1', chr(164):'', chr(165):'', chr(166):'1', chr(167):'', chr(168):'', chr(169):'', chr(170):'', chr(171):'', chr(172):'', chr(173):'', chr(174):'', chr(175):'', chr(176):'0', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'', chr(181):'', chr(182):'', chr(183):'', chr(184):'', chr(185):'1', chr(186):'0', chr(187):'', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'', chr(192):'', chr(193):'', chr(194):'', chr(195):'', chr(196):'', chr(197):'', chr(198):'', chr(199):'', chr(200):'', chr(201):'', chr(202):'', chr(203):'', chr(204):'', chr(205):'1', chr(206):'', chr(207):'1', chr(208):'', chr(209):'', chr(210):'', chr(211):'', chr(212):'0', chr(213):'', chr(214):'0', chr(215):'', chr(216):'0', chr(217):'', chr(218):'', chr(219):'', chr(220):'', chr(221):'', chr(222):'', chr(223):'', chr(224):'', chr(225):'', chr(226):'', chr(227):'', chr(228):'', chr(229):'', chr(230):'', chr(231):'', chr(232):'', chr(233):'', chr(234):'', chr(235):'', chr(236):'', chr(237):'1', chr(238):'', chr(239):'1', chr(240):'0', chr(241):'', chr(242):'', chr(243):'', chr(244):'', chr(245):'0', chr(246):'0', chr(247):'', chr(248):'0', chr(249):'', chr(250):'', chr(251):'', chr(252):'', chr(253):'', chr(254):'', chr(255):''} mappingcharinteger = { chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'', chr(45):'', chr(46):'', chr(47):'', chr(48):'0', chr(49):'1', chr(50):'2', chr(51):'3', chr(52):'4', chr(53):'5', chr(54):'6', chr(55):'7', chr(56):'8', chr(57):'9', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(65):'', chr(66):'', chr(67):'', chr(68):'', chr(69):'', chr(70):'', chr(71):'', chr(72):'', chr(73):'1', chr(74):'', chr(75):'', chr(76):'', chr(77):'', chr(78):'', chr(79):'0', chr(80):'', chr(81):'', chr(82):'', chr(83):'', chr(84):'', chr(85):'', chr(86):'', chr(87):'', chr(88):'', chr(89):'', chr(90):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'', chr(98):'', chr(99):'', chr(100):'', chr(101):'', chr(102):'', chr(103):'', chr(104):'', chr(105):'1', chr(106):'', chr(107):'', chr(108):'1', chr(109):'', chr(110):'', chr(111):'0', chr(112):'', chr(113):'', chr(114):'', chr(115):'', chr(116):'', chr(117):'', chr(118):'', chr(119):'', chr(120):'', chr(121):'', chr(122):'', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'', chr(129):'', chr(130):'', chr(131):'', chr(132):'', chr(133):'', chr(134):'', chr(135):'', chr(137):'', chr(138):'', chr(139):'', chr(140):'0', chr(141):'', chr(142):'', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'', chr(151):'', chr(152):'', chr(153):'', chr(154):'', chr(155):'', chr(156):'0', chr(157):'', chr(158):'', chr(159):'', chr(160):'', chr(161):'1', chr(162):'', chr(163):'1', chr(164):'', chr(165):'', chr(166):'1', chr(167):'', chr(168):'', chr(169):'', chr(170):'', chr(171):'', chr(172):'', chr(173):'', chr(174):'', chr(175):'', chr(176):'0', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'', chr(181):'', chr(182):'', chr(183):'', chr(184):'', chr(185):'1', chr(186):'0', chr(187):'', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'', chr(192):'', chr(193):'', chr(194):'', chr(195):'', chr(196):'', chr(197):'', chr(198):'', chr(199):'', chr(200):'', chr(201):'', chr(202):'', chr(203):'', chr(204):'', chr(205):'1', chr(206):'', chr(207):'1', chr(208):'', chr(209):'', chr(210):'', chr(211):'', chr(212):'0', chr(213):'', chr(214):'0', chr(215):'', chr(216):'0', chr(217):'', chr(218):'', chr(219):'', chr(220):'', chr(221):'', chr(222):'', chr(223):'', chr(224):'', chr(225):'', chr(226):'', chr(227):'', chr(228):'', chr(229):'', chr(230):'', chr(231):'', chr(232):'', chr(233):'', chr(234):'', chr(235):'', chr(236):'', chr(237):'1', chr(238):'', chr(239):'1', chr(240):'0', chr(241):'', chr(242):'', chr(243):'', chr(244):'', chr(245):'0', chr(246):'0', chr(247):'', chr(248):'0', chr(249):'', chr(250):'', chr(251):'', chr(252):'', chr(253):'', chr(254):'', chr(255):''} # NB STR def decodenumber(st,decimal="."): """Extrait un nombre décimal, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" vret=''.join([mappingcharnumber.get(i, i) for i in st]) vret=vret.replace(',',decimal) return vret.replace('.',decimal) # NB STR def decodeinteger(st): """Extrait un nombre entier (purement numérique), à partir d'une chaîne de caractères. Cela est fait d'une manière souple. Exemple : "12-34/56.78|9O" donnera "1234567890" les caractères non numériques sont supprimés les caractères ressemblants sont remplacés par leur équivalent numérique exemples: O => 0 I => 1 l => 1 ce qui permet de corriger des erreurs de saisie. """ return ''.join([mappingcharinteger.get(i, i) for i in st]) # NB STR def forcefloat(st): """Retourne un nombre flottant, d'après une chaîne ; cela est fait d'une manière souple.""" try: signe=1.0 if st.startswith('-'): signe=-1.0 st=st[1:] num=decodenumber(st) vret=signe*float(num) except: vret="" return vret # NB STR def forceint(st): """Retourne un nombre entier, d'après une chaîne ; cela est fait d'une manière souple.""" try: vret=int(decodenumber(st)) except: vret=0 return vret # DT STR def decodedate(st): """Extrait une date, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" st=st.strip() st=st.replace(' ','.') st=''.join([mappingcharnumber.get(i, i) for i in st]) if len(st)<5: a=datetime.date.today().year if len(st)<3: m=datetime.date.today().month j=int(st) else: jm=st if len(jm)==4: j=int(jm[:2]) m=int(jm[-2:]) else: m=int(jm[-2:]) if m>12: j=int(jm[:2]) m=int(jm[-1:]) else: j=int(jm[:1]) else: if st.find('.')>0: try: j,m,a=st.split('.') j,m,a=int(j),int(m),int(a) except: j,m,a=0,0,0 else: if len(st)>6: a=int(st[-4:]) jm=st[:-4] else: a=int(st[-2:]) jm=st[:-2] if len(jm)==4: j=int(jm[:2]) m=int(jm[-2:]) elif len(jm)==2: j=int(jm[:1]) m=int(jm[-1:]) else: m=int(jm[-2:]) if m>12: j=int(jm[:2]) m=int(jm[-1:]) else: j=int(jm[:1]) if a<100: if a<39: a=2000+a else: a=1900+a return datetime.date(a,m,j) # DT STR def decodetime(st): """Extrait un time, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" # a hour m minute j second st=st.strip() st=st.replace(' ','.') st=st.replace(':','.') st=st.replace(',','.') st=st.replace('/','.') st=st.replace('-','.') st=''.join([mappingcharnumber.get(i, i) for i in st]) if len(st)<=5: j = time.localtime()[5] if len(st)<3: m = time.localtime()[4] a = int(st) else: am = st if len(am)>=4: a=int(am[:2]) m=int(am[-2:]) else: m=int(am[-2:]) if m>59: a=int(am[:2]) m=int(am[-1:]) else: a=int(am[:1]) else: if string.find(st,'.')>0: try: a,m,j=string.split(st,'.') a,m,j=int(a),int(m),int(j) except: a,m,j=0,0,0 else: j=int(st[-2:]) am=st[:-2] if len(am)==4: a=int(am[:2]) m=int(am[-2:]) elif len(am)==2: a=int(am[:1]) m=int(am[-1:]) else: m=int(am[-2:]) if m>60: a=int(am[:2]) m=int(am[-1:]) else: a=int(am[:1]) return datetime.time(a,m,j) # DT STR def decodedatetime(st): """Extrait un datetime, à partir d'une chaîne de caractères. Cela est fait d'une manière souple. La séparation entre date et time doit être un espace en retour, on a (date,time) """ s=st.strip() l=len(s) i=s.find(' ') while i<(l/2): i=s.find(' ') d=st[:i] t=st[i+1:] return decodedate(d),decodetime(t) def majssaccent(ch): """ Reformate une chaine en majuscules, sans accents unicode en entrée retourne un unicode """ if not isinstance(ch, (basestring,unicode)): ch=unicode(str(ch)) if not isinstance(ch, unicode): ch=ch.decode("utf-8","replace") s=ch s=s.replace(u"È",u"E") s=s.replace(u"É",u"E") s=s.replace(u"Ê",u"E") s=s.replace(u"Ë",u"E") s=s.replace(u"Ì",u"I") s=s.replace(u"Í",u"I") s=s.replace(u"Î",u"I") s=s.replace(u"Ï",u"I") s=s.replace(u"Ò",u"O") s=s.replace(u"Ó",u"O") s=s.replace(u"Ô",u"O") s=s.replace(u"Ö",u"O") s=s.replace(u"Ù",u"U") s=s.replace(u"Ú",u"U") s=s.replace(u"Û",u"U") s=s.replace(u"Ü",u"U") s=s.replace(u"œ",u"oe") s=s.replace(u"Œ",u"OE") s=s.replace(u"€",u"E") s=s.replace(u"é",u"E") s=s.replace(u"è",u"E") s=s.replace(u"ê",u"E") s=s.replace(u"ë",u"E") s=s.replace(u"à",u"A") s=s.replace(u"â",u"A") s=s.replace(u"ï",u"I") s=s.replace(u"î",u"I") s=s.replace(u"ô",u"O") s=s.replace(u"ö",u"O") s=s.replace(u"ç",u"C") try: s=s.upper() except: s="" for i in u""" ,;'`/\\""": try: s=s.replace(i,'') except: pass return s def forme(valeur,format): vret='' if valeur is not None: if format==format_string: try: vret=valeur except: try: vret=utf81252(valeur) except: try: vret=u1252(valeur) except: vret='?' pass elif format==format_utf8: try: vret=valeur.encode('utf-8','ignore') except: try: vret=uutf8(valeur) except: vret='?' pass elif format==format_majssaccent: try: vret=majssaccent(valeur) vret=utf81252(vret) except: vret=repr(vret) elif format==format_int: try: vret= '%d' % int(valeur) except: vret='' elif format==format_float: try: vret= '%.2f' % float(valeur) except: vret='' elif format==format_date: try: vret=valeur.strftime('%d.%m.%y') except: vret='-erreur date-' pass elif format==format_s_date: try: vret=valeur[8:10]+"."+valeur[5:7]+"."+valeur[0:4] except: vret='-erreur date-' pass elif format==format_date4: try: vret=valeur.strftime('%d.%m.%Y') except: vret='-erreur date-' pass elif format==format_dateouheurejour: try: delai = time.time() - valeur if delai<24*3600: vret=time.strftime('%H:%M',time.localtime(valeur)) else: vret=time.strftime('%d.%m.%y',time.localtime(valeur)) except: vret='-erreur date/time-' pass elif format==format_dateouheurejourhhmm: try: delai = time.time() - valeur if delai<24*3600: vret=time.strftime('%H:%M',time.localtime(valeur)) else: vret=time.strftime('%d.%m.%y %H:%M',time.localtime(valeur)) except: vret='-erreur date/time-' pass elif format==format_datetime4: vret=valeur.strftime('%d.%m.%Y %H:%M') elif format==format_datetime4time: vret=time.strftime("%d.%m.%Y %H:%M", time.gmtime(valeur)) else: vret=repr(valeur) return vret def forcedate(ch): """ Force la conversion d'une date vers le format chaine AAAA.MM.JJ """ sdate=ponx.decodenumber(ch,decimal="") if len(sdate)==1: sdate="0"+sdate if len(sdate)<8: fond=time.strftime("%d%m%Y", time.gmtime()) sdate=sdate+fond[len(sdate):] rdate=sdate[:2]+'.'+sdate[2:4]+'.'+sdate[4:] return rdate def contreforme(valeur,format): vret='' if valeur is not None: if format==format_string: try: vret=unicode(valeur) except: vret=unicode(valeur,'cp1252','replace') elif format==format_utf8: vret=unicode(valeur,'utf-8','replace') elif format==format_majssaccent: try: vret=majssaccent(unicode(valeur)) except: vret=repr(vret) elif format==format_int: vret= forceint(valeur) elif format==format_float: vret= forcefloat(valeur) elif format==format_date: vret=decodedate(valeur) elif format==format_s_date: vret=forcedate(valeur) elif format==format_date4: try: vret=decodedate(valeur) except: vret="???" elif format==format_dateouheurejour: vret=decodedate(valeur) elif format==format_dateouheurejourhhmm: vret=decodedatetime(valeur) elif format==format_datetime4: vret=decodedatetime(valeur) elif format==format_datetime4time: vret=decodedatetime(valeur) else: vret=repr(valeur) return vret """ Quelques codes des touches du clavier VK_LBUTTON : bouton Gauche Souris VK_RBUTTON : bouton Droite Souris VK_MBUTTON : bouton Central Souris VK_CANCEL : Arrêt Exec. programme VK_BACK : Retour Arrière VK_TAB : Tabulation VK_RETURN : Entrée VK_SHIFT : Touche de contrôle MAJ VK_CONTROL : Touche de contrôle CTRL VK_MENU : Touche de contrôle ALT VK_PAUSE : Pause VK_ESCAPE : Echappement VK_SPACE : Barre d'espacement VK_PRIOR : Page Haut VK_NEXT : Page Bas VK_END : Fin VK_HOME : Début VK_LEFT : Flèche gauche VK_UP : Flèche haut VK_RIGHT : Flèche droite VK_DOWN : Flèche bas VK_SNAPSHOT : Impression d'écran VK_INSERT : Insérer VK_DELETE : Supprimer VK_HELP : Aide VK_NUMPAD0..VK_NUMPAD9 : Touche pavé numérique 0 à 9 VK_MULTIPLY : Touche pavé numérique * VK_ADD : Touche pavé numérique + VK_SEPARATOR : Touche pavé numérique Entrée VK_SUBTRACT : Touche pavé numérique - VK_DECIMAL : Touche pavé numérique . (décimal) VK_DIVIDE : Touche pavé numérique / VK_F1..VK_F12 : Touches de fonction F1 à F12 VK_NUMLOCK : Verrouillage pavé numérique VK_SCROLL : Verrouillage scrolling VK_CAPITAL : Verrouillage majuscules Tout: ---- http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx """ def kantislash(): win32api.keybd_event(win32con.VK_RMENU, 0, 0, 0) win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) win32api.keybd_event(ord('8'), 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(ord('8'), 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(win32con.VK_RMENU, 0, win32con.KEYEVENTF_KEYUP, 0) def kdiese(): win32api.keybd_event(win32con.VK_RMENU, 0, 0, 0) win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) win32api.keybd_event(ord('3'), 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.03) win32api.keybd_event(ord('3'), 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.03) win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(win32con.VK_RMENU, 0, win32con.KEYEVENTF_KEYUP, 0) def ktest(): win32api.keybd_event(win32con.VK_SHIFT, 0, 0, 0) win32api.keybd_event(0x54, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.03) win32api.keybd_event(0x54, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.03) win32api.keybd_event(win32con.VK_SHIFT, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.03) def kslash(): win32api.keybd_event(win32con.VK_DIVIDE, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(win32con.VK_DIVIDE, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) def k2points(): win32api.keybd_event(0xBF, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(0xBF, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) def kpoint(): win32api.keybd_event(win32con.VK_DECIMAL, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(win32con.VK_DECIMAL, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) def kstar(): win32api.keybd_event(win32con.VK_MULTIPLY, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(win32con.VK_MULTIPLY, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) def keyb(ch,shift=False,control=False,alt=False, delaik=0.02): for b in ch: if b=='\\': kantislash() elif b=='/': kslash() elif b=='.': kpoint() elif b==':': k2points() elif b=='*': kstar() else: c=b if (b>='A' and b<='Z') or shift: win32api.keybd_event(win32con.VK_SHIFT, 0, 0, 0) if b>='a' and b<='z': c=b.upper() if alt: win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) time.sleep(0.250) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) cord=ord(c) win32api.keybd_event(cord, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(delaik) win32api.keybd_event(cord, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(delaik) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) if alt: win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) if (b>='A' and b<='Z') or shift: win32api.keybd_event(win32con.VK_SHIFT, 0, win32con.KEYEVENTF_KEYUP, 0) def keyd(cod,shift=False,control=False,alt=False): if shift: win32api.keybd_event(win32con.VK_SHIFT, 0, 0, 0) time.sleep(0.01) if alt: win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) time.sleep(0.250) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) win32api.keybd_event(cod, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.02) win32api.keybd_event(cod, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.02) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) if alt: win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.01) if shift: win32api.keybd_event(win32con.VK_SHIFT, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.01) def keyvkcode(vkcode,shift=False,control=False,alt=False): if shift: win32api.keybd_event(win32con.VK_SHIFT, 0, 0, 0) if alt: win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) time.sleep(0.05) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) cod=eval("win32con."+vkcode) win32api.keybd_event(cod, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0) time.sleep(0.05) win32api.keybd_event(cod, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) if control: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) if alt: win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.05) if shift: win32api.keybd_event(win32con.VK_SHIFT, 0, win32con.KEYEVENTF_KEYUP, 0) def mouseclic(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) time.sleep(0.01) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) #time.sleep(0.01) def mousemove(x,y): win32api.SetCursorPos((x,y)) def isnumlock(turn_on) : """ Teste le clavier : si verrouillage-numérique (NumLock) est actif """ return windll.user32.GetKeyState( VK_NUMLOCK ) & 1 def iscapslock(): """ Teste le clavier : si verrouillage-majuscules (CapsLock) est actif """ return ctypes.windll.user32.GetKeyState( win32con.VK_CAPITAL ) & 1 def capture(): """ Capture des touches du clavier, durant un maximum de 120 sec {Maj}{Echap} pour terminer l'enregistrement. utilisé par capturemacro() """ lkey=[7,8,9,10,13] lkey.extend(range(19,255)) bufp=0 deb=time.time() clavt=[] clavc=[] while time.time()-deb<120: win32gui.PumpWaitingMessages() time.sleep(0.001) for k in lkey: if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: ktime=time.time() msg = MSG() while (time.time()-ktime)<0.250: if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: aw=win32gui.GetActiveWindow() while ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), aw, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), aw, 0, 0) time.sleep(0.001) else: break return clavt,clavc if k in (0,129,160,161,162,163,164,165,186,255): continue if win32api.GetAsyncKeyState(k) & 0x8000: if bufp==k: nb_return=0 while win32api.GetAsyncKeyState(k) & 0x8000: nb_return+=1 if nb_return>12: break win32gui.PumpWaitingMessages() time.sleep(0.02) bufp=0 continue bufp=k keycompl="" #if windll.user32.GetKeyState( VK_CAPITAL ) & 1: if iscapslock(): keycompl += "CapsLock+" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" if k in (0,129,160,161,162,163,164,165,186,255): pass else: clavt.append(k) clavc.append(keycompl) def capturemacro(fichier=None): """ Capture un ensemble de touches du clavier, et prépare les données ( on termine par {Maj}{Echapp} ) si fichier is not None, les données sont "cPicklisées" """ ct,cc=capture() for i in range(len(ct)): t=ct[i] c=cc[i] if t>48 and t<90: ct[i]=chr(t).lower() else: pass if fichier is not None: f=open(fichier,'wb') cPickle.dump([ct,cc],f,cPickle.HIGHEST_PROTOCOL) f.close() def clavier(chaine, shift=False,control=False,alt=False, delaik=0.001): """ émule le clavier (envoie des touches du clavier) Exemple : clavier(win32con.VK_RETURN) clavier(u"AZERTYUIOP") clavier(win32con.VK_RETURN) clavier("V",control=True) time.sleep(1) clavier(win32con.VK_F4, alt=True) time.sleep(0.250) clavier(win32con.VK_RIGHT) time.sleep(0.250) clavier(win32con.VK_RETURN) time.sleep(0.250) """ ctypes.windll.user32.VkKeyScanW.restype = ctypes.c_short ctypes.windll.user32.VkKeyScanW.argtypes = [ctypes.c_wchar] DWORD = ctypes.c_ulong LONG = ctypes.c_long WORD = ctypes.c_ushort def LoByte(val): "Return the low byte of the value" return val & 0xff def HiByte(val): "Return the high byte of the value" return (val & 0xff00) >> 8 class MOUSEINPUT(ctypes.Structure): "Needed for complete definition of INPUT structure - not used" _pack_ = 2 _fields_ = [ ('dx', LONG), ('dy', LONG), ('mouseData', DWORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', DWORD), ] assert ctypes.sizeof(MOUSEINPUT) == 24, ctypes.sizeof(MOUSEINPUT) assert ctypes.alignment(MOUSEINPUT) == 2, ctypes.alignment(MOUSEINPUT) class KEYBDINPUT(ctypes.Structure): "A particular keyboard event" _pack_ = 2 _fields_ = [ ('wVk', WORD), ('wScan', WORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', DWORD), ] assert ctypes.sizeof(KEYBDINPUT) == 16, ctypes.sizeof(KEYBDINPUT) assert ctypes.alignment(KEYBDINPUT) == 2, ctypes.alignment(KEYBDINPUT) class HARDWAREINPUT(ctypes.Structure): "Needed for complete definition of INPUT structure - not used" _pack_ = 2 _fields_ = [ ('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD), ] assert ctypes.sizeof(HARDWAREINPUT) == 8, ctypes.sizeof(HARDWAREINPUT) assert ctypes.alignment(HARDWAREINPUT) == 2, ctypes.alignment(HARDWAREINPUT) class UNION_INPUT_STRUCTS(ctypes.Union): "The C Union type representing a single Event of any type" _fields_ = [ ('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT), ] assert ctypes.sizeof(UNION_INPUT_STRUCTS) == 24, ctypes.sizeof(UNION_INPUT_STRUCTS) assert ctypes.alignment(UNION_INPUT_STRUCTS) == 2, ctypes.alignment(UNION_INPUT_STRUCTS) class INPUT(ctypes.Structure): "See: http://msdn.microsoft.com/en-us/library/ms646270%28VS.85%29.aspx" _pack_ = 2 _fields_ = [ ('type', DWORD), ('_', UNION_INPUT_STRUCTS), ] assert ctypes.sizeof(INPUT) == 28, ctypes.sizeof(INPUT) assert ctypes.alignment(INPUT) == 2, ctypes.alignment(INPUT) INPUT_KEYBOARD = 1 KEYEVENTF_EXTENDEDKEY = 1 KEYEVENTF_KEYUP = 2 KEYEVENTF_UNICODE = 4 KEYEVENTF_SCANCODE = 8 VK_SHIFT = 16 VK_CONTROL = 17 VK_MENU = 18 #def k2(touche, **kw): def k2(touche, shift=False,control=False,alt=False, delaik=0.001): """ print 1002,kw if 'shift' in kw: shift=kw['shift'] if 'control' in kw: control=kw['control'] if 'alt' in kw: alt=kw['alt'] if 'delaik' in kw: delaik=kw['delaik'] """ if shift: # appui sur shift inputs = (INPUT * 1)() key=win32con.VK_SHIFT if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_shift,scan_shift = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_shift inputs[0]._.ki.wScan = scan_shift inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if control: # appui sur control inputs = (INPUT * 1)() key=win32con.VK_CONTROL if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_control,scan_control = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_control inputs[0]._.ki.wScan = scan_control inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if alt: # appui sur alt inputs = (INPUT * 1)() key=win32con.VK_MENU if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_alt,scan_alt = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_alt inputs[0]._.ki.wScan = scan_alt inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) # appui sur la touche if isinstance(touche,int): vk,scan = touche, ctypes.windll.user32.MapVirtualKeyW(touche, 0) elif shift or control or alt: vkey_scan = LoByte(ctypes.windll.user32.VkKeyScanW(touche)) vk,scan = vkey_scan, ctypes.windll.user32.MapVirtualKeyW(vkey_scan, 0) else: vk=0 scan=ord(touche) inputs = (INPUT * 2)() flags = KEYEVENTF_UNICODE inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk inputs[0]._.ki.wScan = scan inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE inputs[1].type = INPUT_KEYBOARD inputs[1]._.ki.wVk = vk inputs[1]._.ki.wScan = scan inputs[1]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if delaik>0: time.sleep(delaik) if alt: # relâche control inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_alt inputs[0]._.ki.wScan = scan_alt inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if control: # relâche control inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_control inputs[0]._.ki.wScan = scan_control inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if shift: # relâche shift inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_shift inputs[0]._.ki.wScan = scan_shift inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if isinstance(chaine,int): k2(chaine, shift, control, alt, delaik) else: for c in chaine: k2(c, shift, control, alt, delaik) def playmacro(fichier, delaik=0.01, mode='JOUER'): """ Joue une macro-clavier enregistrée par capturemacro() c'est une émulation du clavier delaik est le délai entre chaque touche (0 = pas de délai) mode='LISTER' permet de voir (print) le contenu de la macro, au lieu de la jouer """ f=open(fichier,'rb') ct,cc = cPickle.load(f) f.close() ttrans={ '1': u'&', "Shift+1": u"1", '2': u'é', "Shift+2": u"2", '3': u'"', "Shift+3": u"3", '4': u"'", "Shift+4": u"4", '5': u'(', "Shift+5": u"5", '6': u'-', "Shift+6": u"6", '7': u'è', "Shift+7": u"7", '8': u'_', "Shift+8": u"8", '9': u'ç', "Shift+9": u"9", '0': u'à', "Shift+à": u"0", '°': u')', "Shift+°": u"°", '+': u'=', "Shift++": u"+", chr(192): u"ù", "Shift+"+chr(192): u"%", chr(220): u"*", "Shift+"+chr(220): u"µ", chr(188): u",", "Shift+"+chr(188): u"?", chr(190): u";", "Shift+"+chr(190): u".", chr(191): u":", "Shift+"+chr(191): u"/", chr(223): u"!", "Shift+"+chr(223): u"§", chr(226): u"<", "Shift+"+chr(226): u">", } ctrans={ '1': "", "Shift+1": "", '2': "", "Shift+2": "", '3': "", "Shift+3": "", '4': "", "Shift+4": "", '5': "", "Shift+5": "", '6': "", "Shift+6": "", '7': "", "Shift+7": "", '8': "", "Shift+8": "", '9': "", "Shift+9": "", '0': "", "Shift+0": "", '°': "", "Shift+°": "", '+': "", "Shift++": "", chr(192): u"", "Shift+"+chr(192): u"", chr(220): u"", "Shift+"+chr(220): u"", chr(188): u"", "Shift+"+chr(188): u"", chr(190): u"", "Shift+"+chr(190): u"", chr(191): u"", "Shift+"+chr(191): u"", chr(223): u"", "Shift+"+chr(223): u"", chr(226): u"", "Shift+"+chr(226): u"", } for t,c in zip(ct,cc): if t==20: continue shift=False control=False alt=False flag_capslock=False if "Shift" in c: shift=True if "Ctrl" in c: control=True if "Alt" in c: alt=True if "CapsLock+" in c: flag_capslock=True if flag_capslock: shift = not shift clef="" if shift: clef+="Shift+" if control: clef+="Ctrl+" if alt: clef+="Alt+" clef+=str(t) if not isinstance(t,int): if clef in ttrans: t=ttrans[clef] c=ctrans[clef] if mode=='LISTER': print "Touche:",t, " shift:",shift," control:",control," alt:",alt else: clavier(t, shift,control,alt, delaik) global flagpreparehtmlmanaged flagpreparehtmlmanaged=False def crevidehtm(url=None): if url is None: url=os.getcwd().replace('\\','/')+"/vide.htm" if not os.path.isfile(url): open(url,"w").write("""
Vide.htm
""") def prparehtmlmanaged(purl=None): global flagpreparehtmlmanaged if purl is None: purl=os.getcwd().replace('\\','/')+"/vide.htm" crevidehtm() url="file:///"+purl.replace('\\/','/') url=url.replace('\\','/') if not url.endswith("/"): url+="/" #alert(url,purl) #os.system('start "" /MIN "'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url) ###subprocess.Popen('"'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url, startupinfo=plance_info) #subprocess.Popen('"'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k -private '+url, startupinfo=info) hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, '"'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url, None, None, 1, win32process.NORMAL_PRIORITY_CLASS, None, None, plance_info) flagpreparehtmlmanaged=True class preparmetric(object): """ s'appelle de la façon suivante : pywig.metric.XXX """ def __init__(self): pass def calcmetric(nom,quoi): temp=eval("win32api.GetSystemMetrics(win32con."+nom+")") setattr(self,nom,temp) calcmetric("SM_CXSCREEN","Largeur écran en pixels") calcmetric("SM_CYSCREEN","Hauteur écran en pixels") calcmetric("SM_CXVSCROLL","Largeur flèche défilement vertical") calcmetric("SM_CYHSCROLL","Hauteur flèche défilement horizontal") calcmetric("SM_CYCAPTION","Hauteur barre de titre") calcmetric("SM_CXBORDER","Largeur bordure fenêtre") calcmetric("SM_CYBORDER","Hauteur bordure fenêtre") calcmetric("SM_CXFIXEDFRAME","Largeur cadre fenêtre dialogue") calcmetric("SM_CYFIXEDFRAME","Hauteur cadre fenêtre dialogue") calcmetric("SM_CYVTHUMB","Hauteur curseur défilement V") calcmetric("SM_CXHTHUMB","Largeur curseur défilement H") calcmetric("SM_CXICON","Largeur icône") calcmetric("SM_CYICON","Hauteur icône") calcmetric("SM_CXCURSOR","Largeur curseur") calcmetric("SM_CYCURSOR","Hauteur curseur") calcmetric("SM_CYMENU","Hauteur barre menus") calcmetric("SM_CXFULLSCREEN","Largeur zone client plein écran") calcmetric("SM_CYFULLSCREEN","Hauteur zone client plein écran") calcmetric("SM_CYKANJIWINDOW","Hauteur fenêtre Kanji") calcmetric("SM_MOUSEPRESENT","Indicateur de présence souris") calcmetric("SM_CYVSCROLL","Hauteur flèche défilement V") calcmetric("SM_CXHSCROLL","Largeur flèche défilement H") calcmetric("SM_DEBUG","Indicateur version débogage") calcmetric("SM_SWAPBUTTON","Indicateur inversion boutons") calcmetric("SM_CXMIN","Largeur fenêtre minimum") calcmetric("SM_CYMIN","Hauteur fenêtre minimum") calcmetric("SM_CXSIZE","Largeur boutons") calcmetric("SM_CYSIZE","Hauteur boutons") calcmetric("SM_CXSIZEFRAME","Largeur bordure fenêtre") calcmetric("SM_CYSIZEFRAME","Hauteur bordure fenêtre") calcmetric("SM_CXMINTRACK","Déplacement H minimum") calcmetric("SM_CYMINTRACK","Déplacement V minimum") calcmetric("SM_CXDOUBLECLK","Tolérance double clic H") calcmetric("SM_CYDOUBLECLK","Tolérance double clic V") calcmetric("SM_CXICONSPACING","Espacement icônes H") calcmetric("SM_CYICONSPACING","Espacement icônes V") calcmetric("SM_MENUDROPALIGNMENT","Déroulement menu G ou D") calcmetric("SM_PENWINDOWS","Extensions stylo installées") calcmetric("SM_DBCSENABLED","Caractères 16 bits autorisés") calcmetric("SM_CMOUSEBUTTONS","Nombre de boutons souris") calcmetric("SM_SECURE","Identificateur de sécurité") calcmetric("SM_CXEDGE","Largeur bordure 3D") calcmetric("SM_CYEDGE","Hauteur bordure 3D") calcmetric("SM_CXMINSPACING","Déplacement H minimum réduction") calcmetric("SM_CYMINSPACING","Déplacement V minimum réduction") calcmetric("SM_CXSMICON","Largeur petites icônes") calcmetric("SM_CYSMICON","Hauteur petites icônes") calcmetric("SM_CYSMCAPTION","Hauteur petites barres") calcmetric("SM_CXSMSIZE","Largeurs petits boutons") calcmetric("SM_CYSMSIZE","Hauteur petits boutons") calcmetric("SM_CXMENUSIZE","Largeur boutons menus") calcmetric("SM_CYMENUSIZE","Hauteur boutons menus") calcmetric("SM_ARRANGE","Agencer boutons réduction") calcmetric("SM_CXMINIMIZED","Largeur fenêtre réduite") calcmetric("SM_CYMINIMIZED","Hauteur fenêtre réduite") calcmetric("SM_CXMAXTRACK","Largeur déplacement maximum") calcmetric("SM_CYMAXTRACK","Hauteur déplacement minimum") calcmetric("SM_CXMAXIMIZED","Largeur fenêtre agrandie") calcmetric("SM_CYMAXIMIZED","Hauteur fenêtre agrandie") calcmetric("SM_NETWORK","Indicateur présence réseau") calcmetric("SM_CLEANBOOT","Boot système") calcmetric("SM_CXDRAG","Inhiber tolérance déplacement x") calcmetric("SM_CYDRAG","Inhiber tolérance déplacement y") calcmetric("SM_SHOWSOUNDS","Sons visuels") calcmetric("SM_CXMENUCHECK","Largeur coche menu") calcmetric("SM_CYMENUCHECK","Hauteur coche menu") calcmetric("SM_SLOWMACHINE","Identificateur processeur lent") calcmetric("SM_MIDEASTENABLED","Identificateur hébreu arabe") calcmetric("SM_MOUSEWHEELPRESENT","Identificateur molette souris") calcmetric("SM_XVIRTUALSCREEN","Origine x écran virtuel") calcmetric("SM_YVIRTUALSCREEN","Origine y écran virtuel") calcmetric("SM_CXVIRTUALSCREEN","Largeur écran virtuel") calcmetric("SM_CYVIRTUALSCREEN","Hauteur écran virtuel") calcmetric("SM_CMONITORS","Nombre de moniteurs") calcmetric("SM_SAMEDISPLAYFORMAT","Identificateur couleur identique") metric=preparmetric() class arbre(object): class item(object): def __init__(self, nom, data, parent=None, image=None, image2=None, coche=None, id=None, idparent=None): self.nom=nom self.data=data self.parent=parent self.image=image self.image2=image2 self.coche=coche self.handle=None self.id=id self.idparent=idparent def __init__(self): self.arbreid=10000 self.items=[] self.ditems={} self.pointeur=-1 def add(self, nom=None, data="...", parent=None, image=None, image2=None, coche=None, insereavant=None): if nom is None: raise ValueError else: if nom in self.items: raise KeyError #existe déjà else: self.arbreid+=1 try: idparent=self.ditems[parent].id except: idparent=None buf=arbre.item( nom, data, parent, image, image2,coche, self.arbreid, idparent) self.ditems[nom]=buf if insereavant is None: self.items.append(nom) else: try: repere = self.items.index(insereavant) self.items.insert(repere,nom) except: self.items.append(nom) def delete(self, nom=None): if nom is not None: if self.nbchild(nom)>0: raise AttributeError # ValueError else: if nom in self.items: i=self.items.index(nom) del(self.ditems[nom]) del(self.items[i]) return True else: raise ValueError def __iter__(self, pnum=None): return self def next(self, pnum=None): if pnum is None: self.pointeur+=1 else: self.pointeur=pnum if self.pointeur>=len(self.items): self.pointeur=-1 raise StopIteration return self.items[self.pointeur], self.ditems[self.items[self.pointeur]] def maxnom(self): # retourne le nom maximum (noms doivent être des entiers) return max(self.items) def itemnom(self,nom): # retourne l'item d'un nom return self.ditems[nom] def parent(self, nom=None): return self.ditems[nom].parent def nbchild(self, nom=None): lenfant=[i for i in self.items if self.ditems[i].parent==nom] return len(lenfant) def listchild(self, nom=None): lenfant=[i.nom for i in self.items if self.ditems[i].parent==nom] return lenfant #--- à voir ------------------------------------------------------------------------------ ''' typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; ''' #--- fin - à voir ------------------------------------------------------------------------ #---evt2--- class POINT(ctypes.Structure): _fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)] def __init__( self, x=0, y=0 ): self.x = x self.y = y class MSG(ctypes.Structure): _fields_ = [('hwnd', ctypes.c_int), ('message', ctypes.c_uint), ('wparam', ctypes.c_int), ('lparam', ctypes.c_int), ('time', ctypes.c_int), ('pt', POINT)] #---evt2--- class win(object): largeurcaractere=10 caption="OUI" class _WIN32MASKEDSTRUCT: def __init__(self, **kw): full_fmt = "" for name, fmt, default, mask in self._struct_items_: self.__dict__[name] = None if fmt == "z": full_fmt += "pi" else: full_fmt += fmt for name, val in kw.iteritems(): if name not in self.__dict__: raise ValueError("LVITEM structures do not have an item '%s'" % (name,)) self.__dict__[name] = val def __setattr__(self, attr, val): if not attr.startswith("_") and attr not in self.__dict__: raise AttributeError(attr) self.__dict__[attr] = val def toparam(self): self._buffs = [] full_fmt = "" vals = [] mask = 0 # calc the mask for name, fmt, default, this_mask in self._struct_items_: if this_mask is not None and self.__dict__.get(name) is not None: mask |= this_mask self.mask = mask for name, fmt, default, this_mask in self._struct_items_: val = self.__dict__[name] if fmt == "z": fmt = "Pi" if val is None: vals.append(0) vals.append(0) else: # Note this demo still works with byte strings. An # alternate strategy would be to use unicode natively # and use the 'W' version of the messages - eg, # LVM_SETITEMW etc. try: val = val + "\0" except: val = str(val) + "\0" if isinstance(val, unicode): val = val.encode("mbcs") str_buf = array.array("b", val) vals.append(str_buf.buffer_info()[0]) vals.append(len(val)) self._buffs.append(str_buf) # keep alive during the call. else: if val is None: val = default vals.append(val) full_fmt += fmt #print 685,'-'*66 #print full_fmt #print tuple(vals) #print 688,'='*66 #sys.exit() return struct.pack(*(full_fmt,) + tuple(vals)) class LVITEM(_WIN32MASKEDSTRUCT): _struct_items_ = [ ("mask", "I", 0, None), ("iItem", "i", 0, None), ("iSubItem", "i", 0, None), ("state", "I", 0, commctrl.LVIF_STATE), ("stateMask", "I", 0, None), ("text", "z", None, commctrl.LVIF_TEXT), ("iImage", "i", 0, commctrl.LVIF_IMAGE), ("lParam", "i", 0, commctrl.LVIF_PARAM), ("iIdent", "i", 0, None), ] class LVCOLUMN(_WIN32MASKEDSTRUCT): _struct_items_ = [ ("mask", "I", 0, None), ("fmt", "i", 0, commctrl.LVCF_FMT), ("cx", "i", 0, commctrl.LVCF_WIDTH), ("text", "z", None, commctrl.LVCF_TEXT), ("iSubItem", "i", 0, commctrl.LVCF_SUBITEM), ("iImage", "i", 0, commctrl.LVCF_IMAGE), ("iOrder", "i", 0, commctrl.LVCF_ORDER), ] # pour customdraw des ListView from ctypes.wintypes import BOOL, HWND, RECT, UINT, DWORD, HDC, DWORD, LPARAM, COLORREF #LPNMHDR class NMHDR(ctypes.Structure): pass INT = ctypes.c_int NMHDR._fields_ = [ ('hwndFrom', HWND), ('idFrom', UINT), ('code', INT) ] LPNMHDR = ctypes.POINTER(NMHDR) #LPNMCUSTOMDRAW class NMCUSTOMDRAW(ctypes.Structure): pass NMCUSTOMDRAW._fields_= [('hdr', NMHDR), ('dwDrawStage', DWORD), ('hdc', ctypes.c_int), ('rc', RECT), ('dwItemSpec', DWORD), ('uItemState', UINT), ('lItemlParam', LPARAM) ] LPNMCUSTOMDRAW = ctypes.POINTER(NMCUSTOMDRAW) #LPNMLVCUSTOMDRAW class NMLVCUSTOMDRAW(ctypes.Structure): pass NMLVCUSTOMDRAW._fields_ = [('nmcd', NMCUSTOMDRAW), ('clrText', COLORREF), ('clrTextBk', COLORREF), ('iSubItem', ctypes.c_int), ('dwItemType', DWORD), ('clrFace', COLORREF), ('iIconEffect', ctypes.c_int), ('iIconPhase', ctypes.c_int), ('iPartId', ctypes.c_int), ('iStateId', ctypes.c_int), ('rcText', RECT), ('uAlign', UINT) ] #LPNMLVCUSTOMDRAW = ctypes.POINTER(NMLVCUSTOMDRAW) # customdraw des TreeView from ctypes.wintypes import BOOL, HWND, RECT, UINT, DWORD, HDC, DWORD, LPARAM, COLORREF class NMHDR(ctypes.Structure): pass INT = ctypes.c_int NMHDR._fields_ = [ ('hwndFrom', HWND), ('idFrom', UINT), ('code', INT) ] LPNMHDR = ctypes.POINTER(NMHDR) class NMCUSTOMDRAW(ctypes.Structure): pass NMCUSTOMDRAW._fields_= [('hdr', NMHDR), ('dwDrawStage', DWORD), ('hdc', ctypes.c_int), ('rc', RECT), ('dwItemSpec', DWORD), ('uItemState', UINT), ('lItemlParam', LPARAM) ] LPNMCUSTOMDRAW = ctypes.POINTER(NMCUSTOMDRAW) class NMTVCUSTOMDRAW(ctypes.Structure): pass NMTVCUSTOMDRAW._fields_ = [('nmcd', NMCUSTOMDRAW), ('clrText', COLORREF), ('clrTextBk', COLORREF), ('iLevel', ctypes.c_int), ] #LPNMTVCUSTOMDRAW = ctypes.POINTER(NMTVCUSTOMDRAW) @staticmethod def champsuivant(h,el,*suite): if suite[0] != 'KEY_Ctrl+': chcourant=h.getfocus() if isinstance(chcourant,win.elementedit): if suite[0]=='KEY_Shift+': chcourant.goprior() else: chcourant.gosuivant() @staticmethod def _GetMaskAndVal(val, default, mask, flag): if val is None: return mask, default else: mask |= flag return mask, val @staticmethod def PackTVINSERTSTRUCT(parent, insertAfter, tvitem): tvitem_buf, extra = win.PackTVITEM(*tvitem) tvitem_buf = tvitem_buf.tostring() format = "ii%ds" % len(tvitem_buf) return struct.pack(format, parent, insertAfter, tvitem_buf), extra @staticmethod def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param): extra =[] mask = 0 mask, hitem = win._GetMaskAndVal(hitem, 0, mask, commctrl.TVIF_HANDLE) mask, state = win._GetMaskAndVal(state, 0, mask, commctrl.TVIF_STATE) if not mask & commctrl.TVIF_STATE: stateMask = 0 mask, text = win._GetMaskAndVal(text, None, mask, commctrl.TVIF_TEXT) mask, image = win._GetMaskAndVal(image, 0, mask, commctrl.TVIF_IMAGE) mask, selimage = win._GetMaskAndVal(selimage, 0, mask, commctrl.TVIF_SELECTEDIMAGE) mask, citems = win._GetMaskAndVal(citems, 0, mask, commctrl.TVIF_CHILDREN) mask, param = win._GetMaskAndVal(param, 0, mask, commctrl.TVIF_PARAM) if text is None: text_addr = text_len = 0 else: text_buffer = array.array("c", text+"\0") extra.append(text_buffer) text_addr, text_len = text_buffer.buffer_info() format = "iiiiiiiiii" buf = struct.pack(format, mask, hitem, state, stateMask, text_addr, text_len, # text image, selimage, citems, param) return array.array("c", buf), extra @staticmethod def EmptyTVITEM(hitem, mask = None, text_buf_size=512): extra = [] # objects we must keep references to if mask is None: mask = commctrl.TVIF_HANDLE | commctrl.TVIF_STATE | commctrl.TVIF_TEXT | commctrl.TVIF_IMAGE | commctrl.TVIF_SELECTEDIMAGE | commctrl.TVIF_CHILDREN | commctrl.TVIF_PARAM if mask & commctrl.TVIF_TEXT: text_buffer = array.array("c", "\0" * text_buf_size) extra.append(text_buffer) text_addr, text_len = text_buffer.buffer_info() else: text_addr = text_len = 0 format = "iiiiiiiiii" buf = struct.pack(format, mask, hitem, 0, 0, text_addr, text_len, # text 0, 0, 0, 0) return array.array("c", buf), extra @staticmethod 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("10i", buffer) 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 item_hItem, item_state, item_stateMask, text, item_image, item_selimage, item_cChildren, item_param @staticmethod def UnpackTVNOTIFY(lparam): format = "iiii40s40s" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, id, code, action, buf_old, buf_new = struct.unpack(format, buf) item_old = win.UnpackTVItem(buf_old) item_new = win.UnpackTVItem(buf_new) return hwndFrom, id, code, action, item_old, item_new @staticmethod def UnpackTVDISPINFO(lparam): format = "iii40s" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, id, code, buf_item = struct.unpack(format, buf) item = win.UnpackTVItem(buf_item) return hwndFrom, id, code, item def __init__(self, titre="miniPyWiG", x=-1,y=-1,l=400,h=300, wclass="PyWiG", parenthandle=None): #win32gui.InitCommonControls() self.hinst = win32gui.dllhandle self.wclass=wclass self.hwnd = None self.hDC = None self.modeinvisible="NORMAL" self.parenthandle = parenthandle self.multigroup=None self.ffille=False self.pyw=False self.origparent=False self.bufkey=None self.navig=None self.etat=None # "MENU" (si menu ouvert) cf si actif ou non (arrière-plan) self.fin=None self.derCommand=None self.derCommandid=None self.timerdebut=time.time() self.timerdelai=0 #en secondes self.timerfonction=None self.mmap=None self.result={} self.bufclick=False self.duree=99999 self.dureeinvisible=3600*12 self.heuredebutinvisible=None self.ligcourante=None self.colcourante=None self.x=int(x) self.y=int(y) self.l=int(l) self.h=int(h) self.hmenu=None self.titre=titre self.fond=None self.fontname = "Arial" # "Comic Sans MS" #"Arial" self.fontsize = "9" self.style_THICKFRAME = True self.style_POPUP = True self.style_VISIBLE = True self.style_CAPTION = True self.style_SYSMENU = False self.style_SETFONT = True self.style_MINIMIZEBOX = True self.style_MAXIMIZEBOX = True self.auto=None self.allobj={} self.menu_item_map={} self.imageList=None self.fonts={} self.add_font(code="DEFAULT", nom="Arial", taille=16, gras=False, italique=0, souligne=0) self.add_font(code="TREEDEFAULT", nom="Arial", taille=18, gras=False, italique=0, souligne=0) self.add_font(code="VLISTDEFAULT", nom="Arial", taille=16, gras=False, italique=0, souligne=0) self.add_font(code="BOUTONDEFAULT", nom="Arial Narrow", taille=20, gras=False, italique=0, souligne=0) self.add_font(code="SOURCE", nom="Courier new", taille=22, gras=False, italique=0, souligne=0) self.runinjected=[] self.grainsdeselflag=0 self.grainsdesel={} self.grainkey={} self.buttons={} self.lbuttons=[] self.edits={} self.ledits=[] self.editcourant=None self.labels={} self.llabels=[] self.months={} self.lmonths=[] self.texts={} self.ltexts=[] self.dessins={} self.ldessins=[] self.images={} self.limages=[] self.pilimages={} self.lpilimages=[] self.ocx={} self.locx=[] self.arbres={} self.larbres=[] self.arbrenomcourant=None self.vlists={} self.lvlists=[] self.scintilla=None self.message_map = { win32con.WM_HOTKEY: self.wmhotkey, #win32con.WM_CHAR: self.TEST, #win32con.WM_GETDLGCODE: self.TEST, win32con.WM_KEYDOWN: self.OnKeyD, win32con.WM_KEYUP: self.OnKey, win32con.WM_LBUTTONDOWN: self.OnLeftClick, win32con.WM_RBUTTONDOWN: self.OnRightClick, win32con.WM_PAINT: self.OnPaint, #win32con.WM_INITDIALOG: self.OnInit, win32con.WM_COMMAND: self.OnCommand, win32con.WM_NOTIFY: self.OnNotify, win32con.WM_CLOSE: self.OnClose, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COPYDATA: self.wmcopydata, } self.message_map = { win32con.WM_HOTKEY: self.wmhotkey, win32con.WM_PAINT: self.OnPaint, win32con.WM_KEYDOWN: self.OnKeyD, #win32con.WM_CHAR: self.OnKeyD, win32con.WM_KEYUP: self.OnKey, win32con.WM_LBUTTONDOWN: self.OnLeftClick, win32con.WM_RBUTTONDOWN: self.OnRightClick, win32con.WM_CTLCOLORSTATIC: self.colorlabel, win32con.WM_CTLCOLOREDIT : self.colorchamp, win32con.WM_COMMAND: self.OnCommand, win32con.WM_NOTIFY: self.OnNotify, win32con.WM_CLOSE: self.OnClose, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COPYDATA: self.wmcopydata, } class cmetric(object): pass metric=cmetric() def __getattr__(self, attr): if hasattr(self.__dict__, attr): return self.__dict__[attr] def __setattr__(self, attr, value): if hasattr(self.__dict__, attr): self.__dict__[attr] = value return self.__dict__[attr] = value def palert(self, txt1="Titre", txt2="", icon=0): if txt2=="": alert(txt1) else: alert(txt2,txt1,icon) def graindeselkey(self,**kw): self.grainsdesel['KEY']=None for k,j in kw.items(): if k.startswith('VK_'): z=eval('win32con.'+k) elif k.startswith('CODE_'): z=int(k[5:]) else: z=ord(k) self.grainkey[z]=j def graindesel(self, *listof): d=iter(listof) for k,j in zip(d,d): self.grainsdesel[k]=j """ except: if k.startswith('_'): self.grainsdesel[k.id])]=j else: self.grainsdesel[k.id]=j """ def settimer(self, fonction=None, duree=12): self.timerdebut=time.time() self.timerdelai=duree #en secondes self.timerfonction=fonction def graindeselv(self, *l): e=iter(l) for k,j in zip(e,e): try: self.grainsdesel[int(k)]=j except: if k.startswith('_'): self.grainsdesel[int(k[1:])]=j else: self.grainsdesel[eval(k)]=j def setprop(self,**kw): if self.parenthandle is None: self.style_CAPTION=True self.style_SYSMENU=False self.style_MINIMIZEBOX=False self.style_MAXIMIZEBOX=False self.style_THICKFRAME=True self.style_POPUP=False for k,j in kw.items(): i=k.upper() if i=='CAPTION': self.style_CAPTION=j elif i=='SYSMENU': self.style_SYSMENU=j elif i=='MINIMIZEBOX': self.style_MINIMIZEBOX = j elif i=='MAXIMIZEBOX': self.style_MAXIMIZEBOX = j elif i=='THICKFRAME': self.style_THICKFRAME = j elif i=='POPUP': self.style_POPUP = j elif i=='X': self.x = j elif i=='Y': self.y = j elif i=='L': self.l = j elif i=='H': self.h = j elif i=='TITRE': self.titre = j elif i=='FONTNAME': self.fontname = j elif i=='FONTSIZE': self.fontsize = j elif i=='FONTTAILLE': self.fontsize = j elif i=='FOND': self.fond = j def aproposde(self,*p): buffocus=self.getfocus() alert("mini-PyWiG"," \t Version "+GlobalPVersion+""" par Michel Claveau Informatique""") time.sleep(0.250) self.active() if buffocus is not None: self.ctrlfocus(buffocus) time.sleep(0.1) def ocxnavig(self,url="http://google.fr"): for e in self.locx: el=self.ocx[e] win32ui.EnableControlContainer() el.fichier=url if not el.fichier.startswith("http") and not el.fichier.startswith("file:"): if os.path.isfile(el.fichier): el.fichier = "file:///"+el.fichier win32gui.PumpWaitingMessages() el.ocx.Navigate(el.fichier) win32gui.PumpWaitingMessages() time.sleep(0.05) def define(self, auto="AUTO"): tempdd=time.time() self.auto=auto if auto=="AUTO": if len(self.ledits)>0: self.auto="OKCANCEL" else: self.auto="OK" if self.parenthandle is None: if self.hmenu is None: self.createmenu(contextmenu=u""" 9000 rien (fermer ce menu) 9001 PyWiG """+ GlobalPVersion +""" image:"""+os.getcwd()+u"""\\ponx.ico 9002 ---- 9100 +Donation 9101 Donner 1 million d'€ 9102 Donner 2 million d'€ image:43 9103 Donner 5 million d'€ 9104 Donner 10 million d'€ 9003 ---- 9004 &Quitter ou Abandonner """) self.graindesel(9001,self.aproposde) self.graindesel(9004,self.ferme) if self.parenthandle is None: if self.auto=="OKCANCEL": CANCEL=self.add_bouton(texte="&Abandon",x=int(self.l/2),y=int(self.h-90),l=100,h=30) OK=self.add_bouton(texte="&OK",x=int(self.l/2-100),y=int(self.h-90),l=100,h=30) self.grainsdesel[OK]=self.valide self.grainsdesel[CANCEL]=self.abandon if self.auto=="OK": OK=self.add_bouton(texte="&OK",x=int(self.l/2-50),y=int(self.h-90),l=100,h=30) self.grainsdesel[OK]=self.abandon # win32con.DS_SETFONT ? #ancien: style = win32con.WS_VISIBLE | win32con.DS_MODALFRAME | win32con.DS_SETFOREGROUND # (le win32con.WS_VISIBLE ralentit la composition du contenu de la fenêtre) style = win32con.DS_MODALFRAME | win32con.DS_SETFOREGROUND if self.style_THICKFRAME: style |= win32con.WS_THICKFRAME #autorise le redimentionnement if self.style_POPUP: style |= win32con.WS_POPUP #pour fenêtre sans bordure if self.style_CAPTION: style |= win32con.WS_CAPTION #barre de titre if self.style_SYSMENU: style |= win32con.WS_SYSMENU #menu système if self.style_MINIMIZEBOX: style |= win32con.WS_MINIMIZEBOX #bouton réduction/restauration/maximisation if self.style_MAXIMIZEBOX: style |= win32con.WS_MAXIMIZEBOX #bouton réduction/restauration/maximisation if self.parenthandle is not None: style |= win32con.WS_CHILD # | win32con.DS_CENTER ? # | win32con.DS_SETFONT ? #if style avec ascenceur (Attn : il faudra gérer les évènements et l'affichage) # style = style | win32con.WS_HSCROLL | win32con.WS_VSCROLL title = self.titre desktop = win32gui.GetDesktopWindow() dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop) centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)/2, (dt_b-dt_t)/2) ) if self.x==-1: self.x=centre_x-(self.l/2) if self.y==-1: self.y=centre_y-(self.h/2) wc = win32gui.WNDCLASS() wc.lpszClassName = self.wclass wc.style = win32con.CS_GLOBALCLASS| win32con.CS_VREDRAW | win32con.CS_HREDRAW # wc.hbrBackground = win32con.COLOR_WINDOW+1 # wc.hbrBackground = win32gui.GetStockObject(win32con.WHITE_BRUSH) # BLACK_BRUSH DKGRAY_BRUSH GRAY_BRUSH LTGRAY_BRUSH WHITE_BRUSH background = ctypes.windll.gdi32.GetStockObject(ctypes.c_int(win32con.LTGRAY_BRUSH)) wc.hbrBackground = background wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) # IDI_APPLICATION IDI_ASTERISK IDI_ERROR IDI_EXCLAMATION IDI_HAND IDI_INFORMATION IDI_QUESTION IDI_WARNING IDI_WINLOGO wc.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) wc.cbWndExtra=0 wc.lpfnWndProc=self.message_map try: class_atom = win32gui.RegisterClass(wc) except: wc.lpszClassName = self.wclass+str(time.time()) class_atom = win32gui.RegisterClass(wc) #---------------------------création-de-la-fenêtre--------------------- self.hwnd = win32gui.CreateWindowEx(0, class_atom, title, style, self.x,self.y, self.l,self.h, 0, 0, self.hinst, None) #self.hwnd = win32gui.CreateWindowEx(0, class_atom, title, style, self.x,self.y, self.l,self.h, desktop, 0, self.hinst, None) if len(self.locx)>0: self.pyw = win32ui.CreateWindowFromHandle(self.hwnd) #---------------------------------------------------------------------- s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s|win32con.WS_EX_LAYERED) #ligne modifiée si on veut travailler en Unicode : #ctypes.windll.user32.SetWindowLongW(self.hwnd, win32con.GWL_EXSTYLE, s|win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(self.hwnd, 0, 255, win32con.LWA_ALPHA) s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.SS_BITMAP for e in self.limages: el=self.images[e] if global_pywin32_version<217: #*2 seulement pour les images... el.hwnd = win32gui.CreateWindow("Static", "", s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) else: el.hwnd = win32gui.CreateWindow("Static", "", s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) #el.hwnd = win32gui.CreateWindow("Static", "", s, el.x*2,el.y*2, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) self.allobj[el.hwnd]=el s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.SS_BITMAP for e in self.lpilimages: el=self.pilimages[e] #el.hwnd = win32gui.CreateWindow("Static", "", s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) if global_pywin32_version<217: #*2 seulement pour les images... el.hwnd = win32gui.CreateWindow("Static", "", s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) else: el.hwnd = win32gui.CreateWindow("Static", "", s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) #el.hwnd = win32gui.CreateWindow("Static", "", s, el.x*2,el.y*2, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) #time.sleep(0.05) self.allobj[el.hwnd]=el if el.fichier!= "": defautpil() el.pilimage = PIL.Image.open(el.fichier) dib = PIL.ImageWin.Dib(el.pilimage) hwnd = PIL.ImageWin.HWND(el.hwnd) dib.draw(hwnd, (0,0, el.l,el.h)) for e in self.locx: el=self.ocx[e] import win32uiole WebBrowserModule = win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) if WebBrowserModule is None: raise ImportError(u"IE non trouvé") class MyWebBrowser(WebBrowserModule.WebBrowser): def __init__(self): self.__dict__["_dispobj_"] = None def CreateControl(self, windowTitle, style, rect, parent, id, lic_string=None): self.hwnd = win32ui.CreateControl(str(self.CLSID), windowTitle, style, rect, parent, id, None, False, lic_string) self.__dict__["_obj_"] = self.hwnd self.dispobj = self.default_interface(win32uiole.GetIDispatchForWindow(self._obj_)) self.__dict__["_dispobj_"] = self.dispobj win32ui.EnableControlContainer() el.ocx = MyWebBrowser() el.hwnd = el.ocx.CreateControl("Web Browser", win32con.WS_TABSTOP | win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_HSCROLL | win32con.WS_VSCROLL | win32con.WS_CLIPSIBLINGS, (el.x,el.y, el.l,el.h), self.pyw, el.id) win32gui.PumpWaitingMessages() el.ocx.Navigate(el.fichier) win32gui.PumpWaitingMessages() self.allobj[el.hwnd]=el for e in self.lvlists: el=self.vlists[e] # win32con.DS_SETFONT | sss = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER sss |= win32con.WS_HSCROLL | win32con.WS_VSCROLL sss |= commctrl.LVS_SINGLESEL | commctrl.LVS_SHOWSELALWAYS #sss |= commctrl.LVS_REPORT #sss |= commctrl.LVS_LIST sss |= commctrl.LVS_ICON #sss |= commctrl.LVS_EDITLABELS s = win32con.WS_CHILD s |= win32con.WS_VISIBLE s |= win32con.WS_BORDER s |= win32con.WS_HSCROLL | win32con.WS_VSCROLL s |= commctrl.LVS_SINGLESEL s |= commctrl.LVS_SHOWSELALWAYS if el.typeaffichage=="REPORT": s |= commctrl.LVS_REPORT elif el.typeaffichage=="LIST": s |= commctrl.LVS_LIST elif el.typeaffichage=="ICON": s |= commctrl.LVS_ICON elif el.typeaffichage=="SMALLICON": s |= commctrl.LVS_SMALLICON else: s |= commctrl.LVS_REPORT s |= commctrl.LVS_SHAREIMAGELISTS #s |= win32con.WS_TABSTOP | win32con.BS_DEFPUSHBUTTON IDC_LISTBOX = 1027 #el.hwnd = win32gui.CreateWindow("SysListView32", "", s, el.x,el.y,el.l,el.h, el.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) el.hwnd = win32gui.CreateWindow("SysListView32", "", s, el.x,el.y,el.l,el.h, self.hwnd, IDC_LISTBOX, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) self.allobj[el.hwnd]=el if el.listimage: if self.imageList is None: self.add_listimage(16, None) #limages = win32gui.SendMessage(el.hwnd, commctrl.LVM_SETIMAGELIST, commctrl.LVSIL_NORMAL, self.imageList) limages = win32gui.SendMessage(el.hwnd, commctrl.LVM_SETIMAGELIST, commctrl.LVSIL_SMALL, self.imageList) ex_style = win32gui.SendMessage(el.hwnd, commctrl.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0) # pour mettre une case à cocher if el.checkmode: ex_style |= commctrl.LVS_EX_CHECKBOXES # si grille: if el.grid: ex_style |= commctrl.LVS_EX_GRIDLINES ex_style |= commctrl.LVS_EX_FULLROWSELECT ex_style |= commctrl.LVS_EX_SUBITEMIMAGES #ex_style |= commctrl.LVS_EX_ONECLICKACTIVATE #ex_style |= commctrl.LVS_EX_TRACKSELECT win32gui.SendMessage(el.hwnd, commctrl.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, ex_style) # list control columns. lvc = win.LVCOLUMN(mask = commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | commctrl.LVCF_SUBITEM) lvc.fmt = commctrl.LVCFMT_LEFT win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts['VLISTDEFAULT'], 0) try: for i in range(len(el.ldata[0])-1,-1,-1): lvc.iSubItem = i lvc.cx = el.collarg[i] win32gui.SendMessage(el.hwnd, commctrl.LVM_INSERTCOLUMN, 0, lvc.toparam()) bufalign='LEFT' for col in range(len(el.ldata[0])): try: atemp=el.aligns[col] if atemp=='': bufalign='LEFT' else: bufalign=atemp except: pass lvc.iSubItem = col if bufalign=='RIGHT': lvc.fmt = commctrl.LVCFMT_RIGHT elif bufalign=='CENTER': lvc.fmt = commctrl.LVCFMT_CENTER else: lvc.fmt = commctrl.LVCFMT_LEFT try: tit=el.coltitle[col] if isinstance(tit, (basestring,unicode)): tit=tit.encode('cp1252','ignore') else: tit=str(tit) lvc.text = tit except: lvc.text = 'col.'+str(col) win32gui.SendMessage(el.hwnd, commctrl.LVM_SETCOLUMN, col, lvc.toparam()) ###self.changelargeur(el, col, 10) self.changelargeur(el, col, el.collarg[col]) except: pass # arrière-plan global du Listview (pour l'arrère-plan des items, voir customdraw, plus bas) win32gui.SendMessage(el.hwnd, commctrl.LVM_SETBKCOLOR, 0, self.color(255,255,255)) # essai de couleur des lignes #win32gui.SendMessage(el.hwnd, commctrl.LVM_FIRST+177, 0, self.color(255,0,0)) s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.SS_LEFT for e in self.llabels: el=self.labels[e] #el.hwnd = win32gui.CreateWindow("Static", el.texte, s, el.x,el.y,el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) if global_pywin32_version<217: #*2 seulement pour les images... el.hwnd = win32gui.CreateWindow("Static", el.texte, s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) else: el.hwnd = win32gui.CreateWindow("Static", el.texte, s, el.x,el.y, el.l,el.h, self.hwnd, 0, win32gui.GetWindowLong(self.hwnd, win32con.GWL_HINSTANCE), None) self.allobj[el.hwnd]=el if el.font != 'DEFAULT': win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts[el.font], 0) """ win32gui.SendMessage(el.hwnd, win32con.WM_CTLCOLORSTATIC, win32api.RGB(0,0,128),0) win32gui.SetTextColor(el.hwnd, win32api.RGB(255,127,0)) win32gui.SendMessage(el.hwnd, win32con.SET_BACKGROUND_COLOR, 0, win32api.RGB(0,0,128)) print 1712 #tmp = win32gui.SetTextColor(el.hwnd, win32api.RGB(127,222,0)) """ """ print 1442 win32gui.SendMessage(el.hwnd, win32con.WM_CTLCOLORSTATIC, 0, win32api.RGB(0,0,128)) print 1444 win32gui.SendMessage(el.hwnd, win32con.WM_CTLCOLORSTATIC, win32api.RGB(0,0,128),0) print 1446 print 1442 win32gui.SendMessage(el.hwnd, win32con.SET_BACKGROUND_COLOR, 0, win32api.RGB(0,0,128)) print 1444 win32gui.SendMessage(el.hwnd, win32con.SET_BACKGROUND_COLOR, win32api.RGB(0,0,128),0) print 1446 print #win32gui.SetTextColor(el.hwnd, win32api.RGB(255,127,0)) #win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, win32api.RGB(255,128,0), 0) """ # win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_TABSTOP # | win32con.ES_MULTILINE | win32con.ES_WANTRETURN cs = win32con.WS_CHILD | win32con.WS_VISIBLE #cs |= win32con.ES_MULTILINE | win32con.ES_WANTRETURN #cs |= win32con.WS_BORDER #cs |= win32con.WS_EX_CONTROLPARENT for e in self.ledits: s=cs s |= win32con.ES_AUTOHSCROLL el=self.edits[e] try: if el.align=='RIGHT': s |= win32con.ES_RIGHT elif el.align=='CENTER': s |= win32con.ES_CENTER else: s |= win32con.ES_LEFT except: pass if el.border: s |= win32con.WS_BORDER if el.multiligne: s |= win32con.ES_MULTILINE #s |= win32con.ES_WANTRETURN if el.mlscroll: #scroll dans le cas du multi-lignes s |= win32con.ES_AUTOHSCROLL | win32con.ES_AUTOVSCROLL #gestion du scroll ou blocage s |= win32con.WS_HSCROLL | win32con.WS_VSCROLL #affichage ascenceurs et translateurs el.hwnd = win32gui.CreateWindow("Edit", "", s, el.x,el.y,el.l,el.h, self.hwnd, 0, self.hinst, None) #el.hwnd = win32gui.CreateWindowEx(0, "Edit", "", s, el.x,el.y,el.l,el.h, self.hwnd, 0, self.hinst, None) self.allobj[el.hwnd]=el if el.font != 'DEFAULT': win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts[el.font], 0) if len(self.ledits)>0: if win32con.VK_RETURN in self.grainkey: pass else: self.graindeselkey(VK_RETURN=win.champsuivant) # http://msdn.microsoft.com/en-us/library/aa453604(v=MSDN.10).aspx s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.BS_PUSHBUTTON # s = s | win32con.BS_DEFPUSHBUTTON # s = s | win32con.WS_TABSTOP # s = s | win32con.BS_VCENTER # BS_TOP BS_BOTTOM # s = s | win32con.BS_CENTER # BS_RIGHT BS_LEFT for e in self.lbuttons: el=self.buttons[e] el.hwnd = win32gui.CreateWindow("Button", el.texte, s, el.x,el.y,el.l,el.h, self.hwnd, 0, self.hinst, None) self.allobj[el.hwnd]=el if el.font != 'DEFAULT': win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts[el.font], 0) else: win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts['BOUTONDEFAULT'], 0) """ if el.textcolor is not None: win32gui.SetTextColor(el.hwnd, win32api.RGB(*el.textcolor)) if el.backcolor is not None: #win32gui.SendMessage(el.hwnd, win32con.SET_BACKGROUND_COLOR, win32api.RGB(255,0,0), 0) win32gui.SetBkMode(el.hwnd, win32con.OPAQUE) win32gui.SetBkColor(el.hwnd, win32api.RGB(*el.backcolor)) #else: # win32gui.SetBkMode(el.hwnd, win32con.TRANSPARENT) """ win32gui.ShowWindow(self.hwnd, win32con.SW_SHOWNORMAL) #ctypes.windll.user32.UpdateWindow(self.hwnd) #win32gui.PumpWaitingMessages() return 0 def destroyedit_isole(self,el): """ détruit le champ isolé el """ win32gui.DestroyWindow(el.hwnd) self.refresh() del self.allobj[el.hwnd] del el def ajoutedit_isole(self,x,y,l,h,multiligne, font=None, callbacksuite=None): """ ajoute, à la volée, un champ de saisie """ cs = win32con.WS_CHILD | win32con.WS_VISIBLE #cs |= win32con.WS_BORDER if multiligne: s |= win32con.ES_MULTILINE #s |= win32con.ES_WANTRETURN s |= win32con.ES_AUTOHSCROLL | win32con.ES_AUTOVSCROLL s |= win32con.WS_HSCROLL | win32con.WS_VSCROLL pass else: s = cs el_editinlist=self.elementedit() el_editinlist.changesuivant(callbacksuite) el_editinlist.x = x el_editinlist.y = y el_editinlist.l = l el_editinlist.h = h el_editinlist.multiligne = multiligne #el_editinlist. = # si bordure : #el_editinlist.hwnd = win32gui.CreateWindow("Edit", "", s, x,y, l,h, self.hwnd, 0, self.hinst, None) el_editinlist.hwnd = win32gui.CreateWindow("Edit", "", s, x+4,y+1, l-4,h-1, self.hwnd, 0, self.hinst, None) if font is not None: win32gui.SendMessage(el_editinlist.hwnd, win32con.WM_SETFONT, self.fonts[font], 0) self.allobj[el_editinlist.hwnd]=el_editinlist return el_editinlist def createmenu(self, contextmenu): self.hmenu = win32gui.CreatePopupMenu() self.allobj[self.hmenu]=self.hmenu lmenu=contextmenu.split('\n') lparent=[0,0,0,0,0,0,0,0] nparent=[0,0,0,0,0,0,0,0] lparent[0]=self.hmenu for litem in lmenu: l=litem.strip() if len(l)>2: if l.startswith('DEFAULT:'): win32gui.SetMenuDefaultItem(self.hmenu, int(l[8:]), 0) else: lig=l try: wid=int(lig[:4]) except: wid=0 if wid>0: self.allobj[wid]=self.hmenu if wid>=9000: suite=lig[4:] if suite.startswith(' '*20): parent=4 elif suite.startswith(' '*16): parent=3 elif suite.startswith(' '*12): parent=2 elif suite.startswith(' '*8): parent=1 else: parent=0 image=None j=suite.find('image:') if j>-1: txt=suite[:j] image=suite[j+6:] image=image.strip() ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON) #image=False try: if image[-4:]=='.ico': hicon = win32gui.LoadImage(0, image, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE) else: shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll") large, small = win32gui.ExtractIconEx(shell_dll, int(image), 1) hicon = small[0] win32gui.DestroyIcon(large[0]) # Add another icon-based icon - this time by converting # via bitmap. Note the icon background when selected is ugly :( hdcBitmap = win32gui.CreateCompatibleDC(0) hdcScreen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y) hbmOld = win32gui.SelectObject(hdcBitmap, hbm) win32gui.SetBkMode(hdcBitmap, win32con.TRANSPARENT) # Fill the background. brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) # unclear if brush needs to be freed. Best clue I can find is: # "GetSysColorBrush returns a cached brush instead of allocating a new # one." - implies no DeleteObject. # draw the icon win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL) win32gui.SelectObject(hdcBitmap, hbmOld) win32gui.DeleteDC(hdcBitmap) except: pass else: txt=suite texte=txt.strip() if texte=='----': item, extras = win32gui_struct.PackMENUITEMINFO(text = "", fType=win32con.MF_SEPARATOR, wID=wid) else: if texte.startswith('+'): lparent[parent+1] = win32gui.CreatePopupMenu() item, extras = win32gui_struct.PackMENUITEMINFO(text=texte[1:], hSubMenu=lparent[parent+1]) else: if image is None: item, extras = win32gui_struct.PackMENUITEMINFO(text = texte, wID=wid) else: try: item, extras = win32gui_struct.PackMENUITEMINFO(text = texte, hbmpItem=hbm.Detach(), wID=wid) except: item, extras = win32gui_struct.PackMENUITEMINFO(text = texte, wID=wid) win32gui.InsertMenuItem(lparent[parent], nparent[parent], True, item) nparent[parent]+=1 class element(object): def __init__(self): pass def hmess(self,par): vret=None try: vret=win32gui.SendMessage(self.hwnd, *par) except: pass return vret def moveraw(self, x,y, l=None,h=None): print 2885 if l is None: l=self.l if h is None: h=self.h print 2890, print self.hwnd,x #win32gui.MoveWindow(self.hwnd, x,y, l,h, 0) win32gui.MoveWindow(self.hwnd, 100,100, 2000,2000, 0) print 2892 def hmess(self,idobj,par): vret=None try: if idobj in self.allobj: vret=win32gui.SendMessage(self.allobj[idobj].hwnd, *par) else: #win32gui.SendMessage(idobj.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_BACKGROUND, self.color(255,255,160)) vret=win32gui.SendMessage(idobj.hwnd, *par) except: pass return vret def add_listimage(self, taillexy=16, lfichiers=None, licones=None, dessins=None, background=win32api.RGB(255,255,255)): #bitmapMask = commctrl.CLR_DEFAULT #bitmapMask = commctrl.CLR_NONE #bitmapMask=win32api.RGB(238,242,251) bitmapMask = background if (lfichiers is None) and (licones is None) and (dessins is None): taillexy=16 #self.bitmapID = win32ui.IDB_DEBUGGER_HIER #self.bitmapID = win32ui.IDB_HIERFOLDERS self.bitmapID = win32ui.IDB_BROWSER_HIER bitmapMask = commctrl.CLR_DEFAULT self.imageListObj = win32ui.CreateImageList(self.bitmapID, taillexy, taillexy, bitmapMask) self.imageList = self.imageListObj.GetSafeHandle() return self.imageList elif licones is not None: self.imageList = win32gui.ImageList_Create( taillexy, taillexy, commctrl.ILC_COLOR32 | commctrl.ILC_MASK, # ILC_COLOR32 1, #initial size 0) # cGrow win32gui.ImageList_SetBkColor(self.imageList, background) nbicones = win32gui.ExtractIconEx(licones[0][0], -1) win32gui.ExtractIconEx(licones[0][0], 0) for fichier,numicon in licones: large, small = win32gui.ExtractIconEx(fichier, numicon) if large != []: win32gui.ImageList_ReplaceIcon(self.imageList, -1, large[0]) # small[0]) ###win32gui.ImageList_AddIcon(self.imageList, win32gui.LoadIcon(hInstance, MAKEINTRESOURCE(101))) win32gui.DestroyIcon(small[0]) win32gui.DestroyIcon(large[0]) return self.imageList elif dessins is not None : self.imageList = win32gui.ImageList_Create( 32, 32, commctrl.ILC_COLOR32, # ILC_COLOR32 1, #initial size 0) # cGrow return self.imageList """ ohdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(ohdc, 32,32) hdc = ohdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.FillSolidRect( (6,6, 26,26), 0x00ffee) #hdc.BitBlt((0,0),(32,32) , hdc, (0,0), win32con.SRCCOPY) hbmp.Paint(hdc) win32gui.ImageList_Add(self.imageList, hbmp.handle, None) #win32gui.ImageList_Replace(self.imageList, -1, ohdc, None) ohdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(ohdc, 32,32) hdc = ohdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.FillSolidRect( (6,6, 26,26), 0xff0000) hbmp.Paint(hdc) win32gui.ImageList_Add(self.imageList, hbmp.handle, None) #win32gui.ImageList_Replace(self.imageList, -1, ohdc, None) """ else: self.imageList = win32gui.ImageList_LoadImage(0, lfichiers[0], taillexy,taillexy, bitmapMask, win32con.IMAGE_BITMAP, win32con.LR_CREATEDIBSECTION | win32con.LR_LOADFROMFILE | win32con.LR_SHARED) win32gui.ImageList_SetBkColor(self.imageList, background) n=-1 for f in lfichiers[1:]: # win32con.LR_CREATEDIBSECTION | win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE) timage=win32gui.LoadImage(0, f, win32con.IMAGE_BITMAP, taillexy,taillexy, win32con.LR_LOADFROMFILE) win32gui.ImageList_Add(self.imageList, timage, None) # bitmapMask) #n+=1 #win32gui.ImageList_Replace(self.imageList, n, tttimage, bitmapMask) return self.imageList def add_font(self, code="fonte", nom="Arial", taille=10, gras=False, italique=0, souligne=0, angle=0): # chargement/préparation de plusieurs fontes+styles font=win32gui.LOGFONT() font.lfFaceName=nom font.lfHeight=taille #font.lfWidth=font.lfHeight/2 font.lfWeight=400 if angle != 0: font.lfEscapement=int(angle*10) font.lfOrientation = int(angle*10) if gras: font.lfWeight=600 font.lfItalic=0 if italique: font.lfItalic=1 font.lfUnderline=0 if souligne: font.lfUnderline=1 self.fonts[code]=win32gui.CreateFontIndirect(font) class elementarbre(element): def __init__(self): pass def redessine(self,data): self.arbredata=data win32gui.InvalidateRect(self.window,None,True) #win32gui.PumpWaitingMessages() def _GetTVItem(self, h): buffer, extra = win.EmptyTVITEM(h) win32gui.SendMessage(self.hwnd, commctrl.TVM_GETITEM, 0, buffer.buffer_info()[0]) return win.UnpackTVItem(buffer.tostring()) def arbrenom(self, nom=1): #retrouve un item par son nom parbre=self.arbredata.ditems[nom] return parbre def getitemnom(self, nom): p=self.arbrenom(nom) contenu = self._GetTVItem(p.handle) return contenu def itemcourant(self): hitem=win32gui.SendMessage(self.hwnd, commctrl.TVM_GETNEXTITEM, commctrl.TVGN_CARET, None) contenu = self._GetTVItem(hitem) #if (contenu[1] | 8192) == contenu[1]: # print u" coché" #else: # print u" NON-coché" return contenu def changecontenu(self, *changements): """ Change le contenu de l'item courant """ htmp=self.itemcourant() lbuf=list(htmp) lchange=iter(changements) for i,j in zip(lchange,lchange): lbuf[i]=j tvitem_buf, extra = win.PackTVITEM(*lbuf) win32gui.SendMessage(self.hwnd, commctrl.TVM_SETITEM, 0, tvitem_buf.buffer_info()[0]) def goitem(self,nom): # retrouve un item par son nom, et va dessus p=self.arbrenom(nom) win32gui.SendMessage(self.hwnd, commctrl.TVM_SELECTITEM, commctrl.TVGN_CARET, p.handle) """ # pour modifier un autre item (repéré par son p.handle) htmp = _GetTVItem(p.handle) lbuf=list(htmp) tvitem_buf, extra = win.PackTVITEM(*lbuf) win32gui.SendMessage(hwndFrom, commctrl.TVM_SETITEM, 0, tvitem_buf.buffer_info()[0]) """ def add_arbre(self, x=None,y=None, l=None,h=None, data=None, checkmode=False, listimage=False, bordure=0, fond=(255,255,255)): el=self.elementarbre() try: der=self.arbres[self.larbres[-1]] el.id=der.id+1 except: der=None el.id=4801 el.window=self.hwnd el.arbredata=data el.checkmode=checkmode el.bordure=bordure # CLIENTEDGE STATICEDGE EDGE_RAISED el.fond=fond el.listimage=listimage # win32gui.ImageList_SetBkColor(self.imageList, background) el.l=l if l is None: if len(self.arbres)==0: el.l=800 else: el.l=der.l el.h=h if h is None: if len(self.arbres)==0: el.h=400 else: el.h=der.h el.x=x if x is None: el.x=0 el.y=y if y is None: el.y=30 self.larbres.append(el.id) self.arbres[el.id]=el self.allobj[el.id]=el return el def add_vlist(self, x=None,y=None, l=None,h=None, largeurs=[5],aligns=['LEFT'],titres=[],ldata=[], checkmode=False, grid=True, listimage=False, fimage=None, colimage=0, formats=[], typeaffichage="REPORT"): el=self.element() try: der=self.vlists[self.lvlists[-1]] el.id=der.id+1 except: der=None el.id=4901 el.ulargeur=largeurs el.aligns=aligns el.coltitle=titres el.ldata=ldata el.checkmode=checkmode el.grid=grid el.listimage=listimage el.fimage=fimage el.colimage=colimage el.typeaffichage=typeaffichage el.hwnd=None el.formats=[] if len(el.ldata)<1: pass #alert(u"Problème",u"Pas de données.") #return el try: for i in range(len(el.ldata[0])): if i0: el.defautlargeur=el.ulargeur[0] try: temp=len(el.ldata[0]) except: temp=len(titres) el.collarg = [el.defautlargeur] * temp el.largeurtotal=0 el.defautlargeur=5 for n in range(temp): try: el.collarg[n] = el.ulargeur[n] el.defautlargeur=el.ulargeur[n] except: el.collarg[n]=el.defautlargeur el.largeurtotal+=el.collarg[n] el.ligcourante=None el.colcourante=None el.l=l if l is None: if len(self.vlists)==0: el.l=800 else: el.l=der.l el.h=h if h is None: if len(self.vlists)==0: el.h=400 else: el.h=der.h el.x=x if x is None: el.x=0 el.y=y if y is None: el.y=30 self.lvlists.append(el.id) self.vlists[el.id]=el self.allobj[el.id]=el return el def add_bouton(self, texte="Bouton",x=None,y=None,l=None,h=None, fonction=None, font='DEFAULT', textcolor=None, backcolor=None): bt=self.element() try: derbt=self.buttons[self.lbuttons[-1]] bt.id=derbt.id+1 except: derbt=None bt.id=3001 bt.texte=texte bt.font=font bt.textcolor=textcolor bt.backcolor=backcolor bt.l=l if l is None: if len(self.buttons)==0: bt.l=80 else: bt.l=derbt.l bt.h=h if h is None: if len(self.buttons)==0: bt.h=25 else: bt.h=derbt.h bt.x=x if x is None: if len(self.buttons)==0: bt.x=10 else: bt.x=derbt.x+derbt.l bt.y=y if y is None: if len(self.buttons)==0: bt.y=self.h-bt.h-10-38 else: bt.y=derbt.y self.lbuttons.append(bt.id) self.buttons[bt.id]=bt if fonction is not None: self.graindesel(bt,fonction) self.allobj[bt.id]=bt return bt def changelabelcontenu(self, el, nouvellevaleur=None): #Change le contenu d'un label ctrl=el.hwnd if not isinstance(nouvellevaleur,str) and not isinstance(nouvellevaleur,unicode): nouvellevaleur=str(nouvellevaleur) try: txt = nouvellevaleur.replace("\r\n", "\n") except: print "Erreur",type(nouvellevaleur) txt = txt.replace("\n", "\r\n") #.decode('utf-8','ignore')) try: txt = txt.encode('cp1252','replace') except: try: txt = txt.encode('utf-8','replace') except: pass result = win32gui.SendMessage(ctrl, win32con.WM_SETTEXT, 0, txt) def changelabelfont(self, el, font): #Change la fonte d'un label ctrl=el.hwnd win32gui.SendMessage(ctrl, win32con.WM_SETFONT, self.fonts[font], 0) def changelabelcouleur(self, el, color=(191,127,0)): #Change la fonte d'un label ctrl=el.hwnd #win32gui.SendMessage(ctrl, win32con.WM_SETFONT, self.fonts[font], 0) result = win32gui.SetTextColor(ctrl, win32api.RGB(*color)) #print 2366,result class elementedit(element): def __init__(self): pass self.valeuraffectee=None def redessine(self): win32gui.InvalidateRect(self.window,None,True) #win32gui.PumpWaitingMessages() def focus(self): ctrl = self.hwnd ctypes.windll.user32.SetFocus(ctrl) win32gui.SendMessage(ctrl, win32con.EM_SETSEL, 255, 255) #pour aller en fin du champ def focusdebut(self): ctrl = self.hwnd ctypes.windll.user32.SetFocus(ctrl) win32gui.SendMessage(ctrl, win32con.EM_SETSEL, 0,0) #pour aller au début du champ def goprior(self): if callable(self.suivant): self.suivant(self,"PRECEDENT") else: ctrl=None for id in self.window.ledits: ctrl=self.window.allobj[id] if ctrl.suivant==self: break if ctrl is None: #ctypes.windll.user32.SetFocus(ctrl) pass else: ctypes.windll.user32.SetFocus(ctrl.hwnd) win32gui.SendMessage(ctrl.hwnd, win32con.EM_SETSEL, 255, 255) #pour aller en fin du champ def gosuivant(self): if callable(self.suivant): self.suivant(self,"SUIVANT") else: ctrl = self.suivant.hwnd if ctrl is None: pass #ctypes.windll.user32.SetFocus(ctrl) else: ctypes.windll.user32.SetFocus(ctrl) win32gui.SendMessage(ctrl, win32con.EM_SETSEL, 255, 255) #pour aller en fin du champ def changesuivant(self, elsuivant): try: self.suivant=elsuivant except: pass def changecontenu(self, nouvellevaleur=None, format=format_string): #Change le contenu du champ ctrl = self.hwnd """ if not isinstance( nouvellevaleur,(str, unicode)): nouvellevaleur=str(nouvellevaleur) try: txt = nouvellevaleur.replace("\r\n", "\n") except: print "Erreur",type(nouvellevaleur) txt = txt.replace("\n", "\r\n") #.decode('utf-8','ignore')) if not isinstance( nouvellevaleur, unicode): try: txt = txt.encode('cp1252','replace') except: try: txt = txt.encode('utf-8','replace') except: pass #result = win32gui.SendMessage(ctrl, win32con.WM_SETTEXT, 0, txt) """ if nouvellevaleur is None: nouvellevaleur=u"" else: nouvellevaleur=forme(nouvellevaleur,format) try: if nouvellevaleur.find('\n')>-1: try: nouvellevaleur = nouvellevaleur.replace("\r\n", "\n") except: pass #print "Erreur 3315",type(nouvellevaleur) nouvellevaleur = nouvellevaleur.replace("\n", "\r\n") if nouvellevaleur.find(u'\n')>-1: try: nouvellevaleur = nouvellevaleur.replace(u"\r\n", u"\n") except: pass #print "Erreur 3322",type(nouvellevaleur) nouvellevaleur = nouvellevaleur.replace(u"\n", u"\r\n") except: pass result = win32gui.SetWindowText(ctrl, nouvellevaleur) def videcontenu(self): #vide le contenu du champ result = win32gui.SendMessage(self.hwnd, win32con.WM_SETTEXT, 0, "") def _getMultipleWindowValues(self, h, getCountMessage, getValueMessage): result = [] VALUE_LENGTH = 1024 #256 bufferlength_int = struct.pack('i', VALUE_LENGTH) valuecount = win32gui.SendMessage(h, getCountMessage, 0, 0) for itemIndex in range(valuecount): valuebuffer = array.array('c', bufferlength_int + " "*(VALUE_LENGTH - len(bufferlength_int))) valueLength = win32gui.SendMessage(h, getValueMessage, itemIndex, valuebuffer) result.append(valuebuffer.tostring()[:valueLength]) return result def fastset(self, nouvellevaleur=None, format=format_string): if nouvellevaleur is None: nouvellevaleur=u"" else: nouvellevaleur=forme(nouvellevaleur,format) """ result = win32gui.SendMessage(self.hwnd, win32con.WM_SETTEXT, 0, txt) """ try: if nouvellevaleur.find('\n')>-1: try: nouvellevaleur = nouvellevaleur.replace(u"\r\n", u"\n") except: pass #print "Erreur",type(nouvellevaleur) nouvellevaleur = nouvellevaleur.replace(u"\n", u"\r\n") except: pass result = win32gui.SetWindowText(self.hwnd, nouvellevaleur) def fast1contenu(self, nouvellevaleur=None, format=format_string): ctrl = self.hwnd """ buf_size = 1 + win32gui.SendMessage(ctrl, win32con.WM_GETTEXTLENGTH, 0, 0) buffer = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(ctrl, win32con.WM_GETTEXT, buf_size, buffer) contenuactuel = buffer[:buf_size] try: self.valeuraffectee=nouvellevaleur.encode('cp1252','ignore') except: try: self.valeuraffectee=str(nouvellevaleur) except: self.valeuraffectee=nouvellevaleur.encode('utf-8','ignore') #print 2367, type(contenuactuel),type(self.valeuraffectee) #if contenuactuel != nouvellevaleur: if contenuactuel != self.valeuraffectee: try: self.changecontenu(self.valeuraffectee) except: pass """ """ buf_size = 1 + win32gui.SendMessage(ctrl, win32con.WM_GETTEXTLENGTH, 0, 0) buffer = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(ctrl, win32con.WM_GETTEXT, buf_size, buffer) contenuactuel = buffer[:buf_size] """ #contenuactuel = unicode(win32gui.GetWindowText(self.hwnd),'cp1252','ignore') bsize = ctypes.windll.user32.GetWindowTextLengthW(self.hwnd) buffer = ctypes.c_wchar_p(' '*bsize) bof = ctypes.windll.user32.GetWindowTextW(self.hwnd, buffer, bsize+1) contenuactuel=contreforme(buffer.value, format) #print 2669,contenuactuel,type(contenuactuel) self.valeuraffectee=nouvellevaleur #print 2853,self.valeuraffectee,nouvellevaleur if contenuactuel != self.valeuraffectee: try: self.changecontenu(self.valeuraffectee, format=format) except: pass def fast1lirecontenu(self, nouvellevaleur=None, format=format_string): bsize = ctypes.windll.user32.GetWindowTextLengthW(self.hwnd) buffer = ctypes.c_wchar_p(' '*bsize) bof = ctypes.windll.user32.GetWindowTextW(self.hwnd,buffer, bsize+1) try: vret=contreforme(buffer.value, format) except: vret="Erreur contreforme 3478" return vret def contenu(self, nouvellevaleur=None, format=format_string): if nouvellevaleur is None: bsize = ctypes.windll.user32.GetWindowTextLengthW(self.hwnd) buffer = ctypes.c_wchar_p(' '*bsize) bof = ctypes.windll.user32.GetWindowTextW(self.hwnd,buffer, bsize+1) return contreforme(buffer.value, format) else: self.valeuraffectee=nouvellevaleur self.changecontenu(self.valeuraffectee,format) def gettext(self): ctrl = self.hwnd buf_size = 1 + win32gui.SendMessage(ctrl, win32con.WM_GETTEXTLENGTH, 0, 0) buffer = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(ctrl, win32con.WM_GETTEXT, buf_size, buffer) return buffer[:buf_size] def replaceselection(self, txt=""): """ Remplace la sélection courante par un texte. Si pas de sélection, insère sous le curseur. Exemple : champ.replaceselection(u"AZ€RTY") """ ctrl = self.hwnd txt = txt.replace("\n", "\r\n") #.decode('utf-8','ignore')) try: txt = txt.encode('cp1252','replace') except: try: txt = txt.encode('utf-8','replace') except: pass result = win32gui.SendMessage(ctrl, win32con.EM_REPLACESEL, 0, txt) def selection(self, debut=None, fin=None): ''' Obtient, ou met, la sélection du champ courant. Exemples: champ.selection(10,33) print champ.selection() (comme ctrlselection, mais méthode de l'objet champ) ''' if debut is None: debut=ctypes.c_long(0) fin=ctypes.c_long(0) temp = win32gui.SendMessage(self.hwnd, win32con.EM_GETSEL, debut,fin) return(debut.value,fin.value) ''' une autre façon de faire: class I(ctypes.Structure): _fields_=[('x', ctypes.c_long)] debut=I() fin=I() temp = win32gui.SendMessage(self.hwnd, win32con.EM_GETSEL, debut,fin) return(debut.x,fin.x) ''' else: if fin is None: fin=debut win32gui.SendMessage(self.hwnd, win32con.EM_SETSEL, debut, fin) def getpositionchar(self, nb=None): """ Donne la position X,Y (en pixels) du caractère (n°) donné en paramètre. Cette position est relative au controle (au champ). """ if nb is None: nb=self.selection()[0] class XY(ctypes.Structure): _fields_=[('x', ctypes.c_long),('y', ctypes.c_long)] xy=XY() temp = win32gui.SendMessage(self.hwnd, win32con.EM_POSFROMCHAR, nb, xy) return(temp-int(temp/65536)*65536, int(temp/65536)) def firstvisibleline(self): """ Fournit le numéro de la 1ère ligne visible """ return win32gui.SendMessage(self.hwnd, win32con.EM_GETFIRSTVISIBLELINE, 0,0) def carindexline(self, num=0): """ Fournit le numéro du 1ère caractère de la ligne num """ return win32gui.SendMessage(self.hwnd, win32con.EM_LINEINDEX, num,0) def linelongueur(self, num=0): """ Donne la longueur (en car.) de la ligne contenant le caractère n° num) """ return win32gui.SendMessage(self.hwnd, win32con.EM_LINELENGTH, num,0) def undoredo(self): return win32gui.SendMessage(self.hwnd, win32con.EM_UNDO, 0,0) def scrollline(self, nb=1): """ 'scrolle' le champ multi-lignes de nb lignes, vers la haut ou vers le bas (si nb<0) """ if nb>0: sens=win32con.SB_LINEDOWN else: sens=win32con.SB_LINEUP nb=-nb for i in range(nb): result = win32gui.SendMessage(self.hwnd, win32con.EM_SCROLL, sens, 0) def scrollpage(self, nb=1): """ 'scrolle' le champ multi-lignes de nb pages, vers la haut ou vers le bas (si nb<0) """ if nb>0: sens=win32con.SB_PAGEDOWN else: sens=win32con.SB_PAGEUP nb=-nb for i in range(nb): result = win32gui.SendMessage(self.hwnd, win32con.EM_SCROLL, sens, 0) def linefromcar(self, num): """ retourne le n° de la ligne contenant le caractère n° num """ return win32gui.SendMessage(h, win32con.EM_LINEFROMCHAR, num, 0) def longmax(self, nb=None): """ Retourne ou change le nb maxi de caractères que l'on peut saisir """ if nb is None: return win32gui.SendMessage(self.hwnd, win32con.EM_GETLIMITTEXT, 0, 0) else: win32gui.SendMessage(self.hwnd, win32con.EM_SETLIMITTEXT, nb, 0) def statistics(self): """ retourne quelques informations sur le (contenu du) champ : taille ; en nb de caractères nb lignes n° ligne courante """ h=self.hwnd taille = win32gui.SendMessage(h, win32con.WM_GETTEXTLENGTH, 0, 0) nblig = win32gui.SendMessage(h, win32con.EM_GETLINECOUNT, 0, 0) sel=self.selection() ligcourante = win32gui.SendMessage(h, win32con.EM_LINEFROMCHAR, sel[0], 0) #ligcourante = win32gui.SendMessage(h, win32con.EM_GETLINE, 0, 0) return(taille,nblig,ligcourante) def move(self,x,y,l=None,h=None): """ Change position et taille du champ """ if l is None: l=self.l if h is None: h=self.h win32gui.MoveWindow(self.hwnd, x,y, l,h, 0) def movevl(self,x,y,l=None,h=None): """ Change position et taille du champ volant dans un VList (ListView) """ if l is None: l=self.l if h is None: h=self.h win32gui.MoveWindow(self.hwnd, x+4,y+1, l-4,h-1, 0) class survligne(object): def __init__(self, w, lvid, cols=[0], font=None): self.indexcol = 0 self.w = w self.lvid = lvid self.cols = cols self.font = font self.champ = None def suiteisole(self, elchamp, *par): col = self.w.colcourante lig = self.w.ligcourante self.w.setcellule(self.lvid, lig,col, elchamp.contenu()) if par[0] == 'SUIVANT': self.indexcol +=1 if self.indexcol >= len(self.cols): self.w.destroyedit_isole(elchamp) self.w.ctrlfocus(self.lvid) time.sleep(0.05) return elif par[0] == 'PRECEDENT': self.indexcol -=1 if self.indexcol<0: self.indexcol=0 self.saisiecellule(lig, self.cols[self.indexcol]) def saisiecellule(self, ligne, col): self.w.colcourante=col x,y,xx,yy = self.w.lvgetcellrect(self.lvid, ligne, col) if self.champ is None: self.champ = self.w.ajoutedit_isole( x+self.lvid.x,y+self.lvid.y, xx-x,yy-y, multiligne = False, font = self.font, callbacksuite = self.suiteisole) else: self.champ.movevl(x+self.lvid.x,y+self.lvid.y, xx-x,yy-y) lc_contenu = self.w.lvreadligcol(self.lvid, ligne, col) self.champ.contenu(lc_contenu) self.w.ctrlfocus(self.champ) time.sleep(0.01) def saisie(self, ligne=0): self.saisiecellule(ligne, self.cols[self.indexcol]) def add_edit(self, x=None,y=None,l=None,h=None, multiligne=False, border=True, mlscroll=False, font='DEFAULT', format=0, align='LEFT', g_lig=-1, g_col=-1): el=self.elementedit() try: der=self.edits[self.ledits[-1]] el.id=der.id+1 except: der=None el.id=2001 el.window=self el.multiligne=multiligne el.mlscroll=mlscroll el.border=border el.format=format el.align=align el.font=font el.g_lig=g_lig el.g_col=g_col el.l=l if l is None: if len(self.edits)==0: el.l=200 else: el.l=der.l el.h=h if h is None: if len(self.edits)==0: el.h=22 else: el.h=der.h el.x=x if x is None: if len(self.edits)==0: el.x= int(self.l/2)-50 else: el.x=der.x el.y=y if y is None: if len(self.edits)==0: el.y=20 #40 else: el.y=der.y+der.h+5 if len(self.ledits)>0: self.edits[self.ledits[-1]].suivant=el self.ledits.append(el.id) self.edits[el.id]=el self.allobj[el.id]=el el.suivant=self.edits[self.ledits[0]] return el def add_editborder(self,el, color="192 192 192"): self.add_dessin("color "+color+""" pen 0 1 brush 255 255 255 rectangle """+str(el.x-1)+" "+str(el.y-1)+" "+str(el.l+el.x)+" "+str(el.h+el.y)+""" """) def add_label(self, texte="Label", x=None,y=None,l=None,h=None, multiligne=False, font='DEFAULT', fond=None): el=self.element() try: der=self.labels[self.llabels[-1]] el.id=der.id+1 except: der=None el.id=2501 el.texte=texte el.multiligne=multiligne el.font=font el.l=l if l is None: if len(self.labels)==0: el.l=100 else: el.l=der.l el.h=h if h is None: if len(self.labels)==0: el.h=22-2 else: el.h=der.h el.x=x if x is None: if len(self.labels)==0: el.x= int(self.l/2)-100-22-2-30 else: el.x=der.x el.y=y if y is None: if len(self.labels)==0: el.y=20+1 #40+1 else: el.y=der.y+der.h+5+1-1 self.llabels.append(el.id) self.labels[el.id]=el self.allobj[el.id]=el return el def add_month(self, year=2010, month=3, day=31, x=None,y=None, l=218,h=184): el=self.element() try: der=self.months[self.lmonths[-1]] el.id=der.id+1 except: der=None el.id=5101 el.year=year el.month=month el.day=day el.l=l el.h=h el.x=x el.y=y self.lmonths.append(el.id) self.months[el.id]=el self.allobj[el.id]=el return el def add_inkedit(self, x=None,y=None, l=300,h=200): el=self.element() try: der=self.months[self.lmonths[-1]] el.id=der.id+1 except: der=None el.id=5101 el.l=l el.h=h el.x=x el.y=y self.lmonths.append(el.id) self.months[el.id]=el self.allobj[el.id]=el return el def add_text(self, texte="Texte", x=None,y=None,l=None,h=None, multiligne=False, font=None, textcolor=(192,0,0), backcolor=None, align='LEFT', valign='TOP', g_lig=-1, g_col=-1): el=self.element() try: der=self.texts[self.ltexts[-1]] el.id=der.id+1 except: der=None el.id=3501 el.texte=texte el.win=self el.multiligne=multiligne el.font=font el.textcolor=textcolor el.backcolor=backcolor el.align=align el.valign=valign el.g_lig=g_lig el.g_col=g_col el.l=l if l is None: if len(self.texts)==0: el.l=int(self.h*0.80) else: el.l=der.l el.h=h if h is None: if len(self.texts)==0: el.h=22 else: el.h=der.h el.x=x if x is None: if len(self.texts)==0: el.x= int(self.l/2)-int(el.l/2)-10 else: el.x=der.x el.y=y if y is None: if len(self.texts)==0: el.y=40+1 else: el.y=der.y+der.h+5+1 self.ltexts.append(el.id) self.texts[el.id]=el self.allobj[el.id]=el return el def add_dessin(self, listeinstructions): el=self.element() try: der=self.dessins[self.ldessins[-1]] el.id=der.id+1 except: der=None el.id=6001 el.dessin=listeinstructions self.ldessins.append(el.id) self.dessins[el.id]=el self.allobj[el.id]=el return el def add_image(self, fichier=None, x=0,y=0,l=0,h=0): el=self.element() try: der=self.images[self.limages[-1]] el.id=der.id+1 except: der=None el.id=4001 el.fichier=fichier el.l=l el.h=h el.x=x el.y=y self.limages.append(el.id) self.images[el.id]=el self.allobj[el.id]=el return el def add_pilimage(self, fichier=None, x=0,y=0,l=0,h=0): defautpil() try: test=PIL except: raise ImportError return el=self.element() try: der=self.pilimages[self.lpilimages[-1]] el.id=der.id+1 except: der=None el.id=4501 el.fichier=fichier el.l=l el.h=h el.x=x el.y=y self.lpilimages.append(el.id) self.pilimages[el.id]=el self.allobj[el.id]=el return el def add_ocx(self, fichier=None, x=0,y=0,l=0,h=0): el=self.element() try: der=self.ocx[self.locx[-1]] el.id=der.id+1 except: der=None el.id=4991 if not fichier.startswith("http") and not fichier.startswith("file:"): if os.path.isfile(fichier): fichier = "file:///"+fichier el.fichier=fichier el.l=l el.h=h el.x=x el.y=y self.locx.append(el.id) self.ocx[el.id]=el self.allobj[el.id]=el return el def moveraw(self,x,y,l=None,h=None): if l is None: l=self.l if h is None: h=self.h win32gui.MoveWindow(self.hwnd, x,y, l,h, 0) def move(self, x,y, l=None,h=None): if l is None: l=self.l if h is None: h=self.h win32gui.MoveWindow(self.hwnd, x,y, l,h, 0) self.refresh() def gettaille(self): x,y,l,h = win32gui.GetWindowRect(self.hwnd) return(x,y,l-x,h-y) def settitle(self,tit=None): if tit is not None: win32gui.SetWindowText(self.hwnd, tit) def visible(self,pvisible=True): if pvisible: win32gui.ShowWindow(self.hwnd, win32con.SW_SHOWNORMAL) ###win32gui.PumpWaitingMessages() win32gui.UpdateWindow(self.hwnd) ###win32gui.PumpWaitingMessages() else: win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE) def isvisible(self): return win32gui.IsWindowVisible(self.hwnd) def ferme(self, *p): global flagpreparehtmlmanaged if len(self.locx)>0: for a in self.locx: el=self.ocx[a] win32gui.SendMessage(el.hwnd, win32con.WM_CLOSE, 0,0) time.sleep(0.1) self.locx=[] if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) time.sleep(0.1) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False self.mmclose() self.duree=0 try: win32gui.DestroyWindow(self.hwnd) except: pass def fermegauche(self, *p): """ ferme la fenêtre avec un effet de glissement accéléré vers la gauche à utiliser de préférence pour des fenêtres de taille peu importante. """ global flagpreparehtmlmanaged if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) time.sleep(0.250) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False #alert("2086", str(flagpreparehtmlmanaged)) xx=self.x for i in range(10): xx-=10 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(20): xx-=20 if xx<-self.l: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(20): xx-=45 if xx<-self.l: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) for i in range(10): xx-=80 if xx<-self.l: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) self.mmclose() self.duree=0 try: win32gui.DestroyWindow(self.hwnd) except: pass def fermegaucherapide(self, *p): """ ferme la fenêtre avec un effet de glissement accéléré vers la gauche à utiliser de préférence pour des fenêtres de taille peu importante. """ global flagpreparehtmlmanaged if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) #time.sleep(0.1) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False #alert("2086", str(flagpreparehtmlmanaged)) xx=self.x for i in range(3): xx-=10 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) win32gui.PumpWaitingMessages() for i in range(4): xx-=20 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(50): xx-=80 if xx<-self.l: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) self.mmclose() self.duree=0 try: win32gui.DestroyWindow(self.hwnd) except: pass def fermedroite(self, *p): """ ferme la fenêtre avec un effet de glissement accéléré vers la droite à utiliser de préférence pour des fenêtres de taille peu importante. """ global flagpreparehtmlmanaged if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) time.sleep(0.250) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False #alert("2086", str(flagpreparehtmlmanaged)) xx=self.x for i in range(5): xx+=5 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(10): xx+=10 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(10): xx+=20 if xx>1400: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) for i in range(15): xx+=80 if xx>1400: break win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) self.mmclose() self.duree=0 try: win32gui.DestroyWindow(self.hwnd) except: pass def ouvregaucherapide(self, x, *p): """ ouvre la fenêtre par un effet de glissement accéléré depuis la gauche à utiliser de préférence pour des fenêtres de taille peu importante. """ global flagpreparehtmlmanaged if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) time.sleep(0.1) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False #alert("2086", str(flagpreparehtmlmanaged)) xx=x - 3*10 - 4*20 # - 10*80 nb80 = int((self.l+xx)/80+0.99) xx = xx-nb80*80 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) for i in range(nb80): xx+=80 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 0) time.sleep(0.01) for i in range(4): xx+=20 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) for i in range(3): xx+=10 win32gui.MoveWindow(self.hwnd, xx,self.y, self.l,self.h, 1) time.sleep(0.01) self.x=x win32gui.MoveWindow(self.hwnd, self.x,self.y, self.l,self.h, 1) def ouvrehautrapide(self, y, *p): """ ouvre la fenêtre par un effet de glissement accéléré depuis le haut à utiliser de préférence pour des fenêtres de taille peu importante. """ global flagpreparehtmlmanaged if self.ffille: try: win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) time.sleep(0.1) #win32gui.DestroyWindow(self.ffille) except: pass self.ffille=False flagpreparehtmlmanaged=False #alert("2086", str(flagpreparehtmlmanaged)) pas=25 yy=y - 3*10 - 5*20 # - 10*80 nb80 = int((self.h+yy)/pas+1.99) yy = yy-nb80*pas win32gui.MoveWindow(self.hwnd, self.x,yy, self.l,self.h, 1) win32gui.PumpWaitingMessages() for i in range(nb80): yy+=pas win32gui.MoveWindow(self.hwnd, self.x,yy, self.l,self.h, 1) #time.sleep(0.001) win32gui.PumpWaitingMessages() for i in range(5): yy+=20 win32gui.MoveWindow(self.hwnd, self.x,yy, self.l,self.h, 1) time.sleep(0.01) win32gui.PumpWaitingMessages() for i in range(3): yy+=10 win32gui.MoveWindow(self.hwnd, self.x,yy, self.l,self.h, 1) time.sleep(0.02) win32gui.PumpWaitingMessages() self.y=y win32gui.MoveWindow(self.hwnd, self.x,self.y, self.l,self.h, 1) win32gui.PumpWaitingMessages() time.sleep(0.01) def destroyctrl(self, id): ctrl = win32gui.GetDlgItem(self.hwnd, id) win32gui.DestroyWindow(ctrl) self.refresh() if id in self.buttons: del self.buttons[id] del self.lbuttons[self.lbuttons.index(id)] if id in self.edits: del self.edits[id] del self.ledits[self.ledits.index(id)] if id in self.labels: del self.labels[id] del self.llabels[self.llabels.index(id)] if id in self.months: del self.months[id] del self.lmonths[self.lmonths.index(id)] if id in self.texts: del self.texts[id] del self.ltexts[self.ltexts.index(id)] if id in self.dessins: del self.dessins[id] del self.ldessins[self.ldessins.index(id)] if id in self.images: del self.images[id] del self.limages[self.limages.index(id)] if id in self.pilimages: del self.pilimages[id] del self.lpilimages[self.lpilimages.index(id)] if id in self.ocx: del self.ocx[id] del self.locx[self.locx.index(id)] if id in self.arbres: del self.arbres[id] del self.larbres[self.larbres.index(id)] if id in self.vlists: del self.vlists[id] del self.lvlists[self.lvlists.index(id)] del self.allobj[el.id] def isactive(self, *p): """ est-ce que la fenêtre est celle active """ temph=win32gui.GetActiveWindow() if temph==self.hwnd: return(True) else: return(False) def isfocus(self, *p): """ est-ce que la fenêtre qui a le focus ? """ temph=win32gui.GetFocus() if temph==self.hwnd: return(True) else: return(False) def active(self, *p): """ met la fenêtre au premier plan, et l'active """ global wtop try: win32gui.SetForegroundWindow(self.hwnd) win32gui.SetActiveWindow(self.hwnd) except: pass #print "erreur en",2924 wtop=None def settop(self, *p): """ met la fenêtre au premier plan (sans l'activer) """ global wtop try: win32gui.SetForegroundWindow(self.hwnd) except: pass wtop=None def activetopsimple(self, *p): """ met la fenêtre au premier plan, sans toucher au wtop """ global wtop try: win32gui.SetForegroundWindow(self.hwnd) time.sleep(0.01) win32gui.SetActiveWindow(self.hwnd) except: pass wtop=None def activetop(self, *p): """ met la fenêtre au premier plan """ global wtop try: win32gui.SetForegroundWindow(self.hwnd) win32gui.SetActiveWindow(self.hwnd) wtop=self except: pass def ctrlfocus(self, el): try: ctypes.windll.user32.SetFocus(el.hwnd) #win32gui.PumpWaitingMessages() win32gui.SendMessage(el.hwnd, win32con.EM_SETSEL, 255, 255) #pour aller en fin du champ except: pass def ctrlfocusdebut(self, el): try: ctypes.windll.user32.SetFocus(el.hwnd) #win32gui.PumpWaitingMessages() win32gui.SendMessage(el.hwnd, win32con.EM_SETSEL, 0,0) #pour aller en fin du champ except: pass def ctrlclick(self, el): ctrl = el.hwnd #print 1415,el.x,el.y, el.l,el.h alert(u"à faire") #ctypes.windll.user32.SetFocus(ctrl) def ctrlselection(self, el, debut=None, fin=None): ''' Obtient, ou met, la sélection pour un champ donné. Exemples: w.ctrlselection(champ1, 10,33) print w.ctrlselection(champ2) ''' if debut is None: debut=ctypes.c_long(0) fin=ctypes.c_long(0) temp = win32gui.SendMessage(el.hwnd, win32con.EM_GETSEL, debut,fin) return(debut.value,fin.value) ''' une autre façon de faire: class I(ctypes.Structure): _fields_=[('x', ctypes.c_long)] debut=I() fin=I() temp = win32gui.SendMessage(el.hwnd, win32con.EM_GETSEL, debut,fin) return(debut.x,fin.x) ''' else: if fin is None: fin=debut win32gui.SendMessage(el.hwnd, win32con.EM_SETSEL, debut, fin) def setback(self): #win32gui.SetWindowPos(self.hwnd, win32con.HWND_BOTTOM, self.x,self.y, self.l,self.h, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE) stylecourant = win32api.GetWindowLong(self.hwnd, win32con.GWL_STYLE) win32gui.SetWindowPos(self.hwnd, win32con.HWND_BOTTOM, self.x,self.y, self.l,self.h, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE) def ctrlsetposition(self, el, x,y, l=None,h=None): """ Change position et taille du champ """ if l is None: l=el.l if h is None: h=el.h #stylecourant = win32api.GetWindowLong(el.hwnd, win32con.GWL_STYLE) win32gui.SetWindowPos(el.hwnd, win32con.HWND_BOTTOM, el.x,el.y, el.l,el.h, win32con.SWP_NOSIZE) def wtest(self): """ supprime barre de titre et bordure """ style = win32con.WS_DLGFRAME | win32con.WS_BORDER current = win32api.GetWindowLong(self.hwnd, win32con.GWL_STYLE) win32api.SetWindowLong(self.hwnd, win32con.GWL_STYLE, style ^ current) win32gui.SetWindowPos(self.hwnd, 0, self.x-12,self.y-12, self.l-16, self.h-200, win32con.SWP_FRAMECHANGED | win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOZORDER) #win32gui.SetWindowPos(self.hwnd, 0, 0,0, 0,0, win32con.SWP_FRAMECHANGED | win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOZORDER) win32gui.PumpWaitingMessages() def getfocus(self): # retourne le champ qui a le focus (pas dans les ListViews) # peur aussi retourner ctrl=ctypes.windll.user32.GetFocus() try: vret=self.allobj[ctrl] except: if ctrl==self.hwnd: vret=self else: vret=None return vret def alert(self,txt1="Titre",txt2="",icon=0): alert(txt1,txt2,icon) def changeimage(self, el, fichier): ext=fichier[-3:].upper() if ext=="BMP": self.image = win32gui.LoadImage(self.hinst, fichier, win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE) win32gui.SendMessage(el.hwnd, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, self.image) el.fichier=fichier self.refresh() elif ext=="JPG" or ext=="PEG" or ext=="PNG" or ext=="GIF": gdi = ctypes.windll.gdiplus ole32 = ctypes.windll.ole32 kernel32 = ctypes.windll.kernel32 BOOL = ctypes.c_int class GdiplusStartupInput(ctypes.Structure): _fields_ = [ ('GdiplusVersion', ctypes.c_uint32), ('DebugEventCallback', ctypes.c_void_p), ('SuppressBackgroundThread', BOOL), ('SuppressExternalCodecs', BOOL) ] class GdiplusStartupOutput(ctypes.Structure): _fields = [ ('NotificationHookProc', ctypes.c_void_p), ('NotificationUnhookProc', ctypes.c_void_p) ] class CLSID(ctypes.Structure): _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16), ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_uint8 * 8)] def __init__(self, *args): if len(args) == 1: part1, part2, part3, part4, part5 = args[0].split('-') self.Data1 = int(part1, 16) self.Data2 = int(part2, 16) self.Data3 = int(part3, 16) self.Data4[0] = int(part4[0:2], 16) self.Data4[1] = int(part4[2:4], 16) for i in range(6): self.Data4[i+2] = int(part5[i*2:i*2+2], 16) Structure.__init__(self) else: Structure.__init__(self, *args) def __str__(self): return '%08x-%04x-%04x-%s' % (int(self.Data1), int(self.Data2), int(self.Data3), '%02x%02x-%02x%02x%02x%02x%02x%02x' % tuple(self.Data4)) class EncoderParameter(ctypes.Structure): _fields_ = [ ('GUID', CLSID), ('NumberOfValues', ctypes.c_uint32), ('type', ctypes.c_int), #EncoderParameterValueType ('value', ctypes.c_uint32), ] class EncoderParameters(ctypes.Structure): _fields_ = [ ('count', ctypes.c_uint32), ('Parameter', EncoderParameter), ] i = GdiplusStartupInput() o = GdiplusStartupOutput() token = ctypes.c_ulong() i.GdiplusVersion = 1 gdi.GdiplusStartup(ctypes.byref(token), ctypes.byref(i), ctypes.byref(o)) data = open(fichier,"rb").read() # Create a HGLOBAL with image data GMEM_MOVEABLE = ctypes.c_int(2) hglob = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data)) ptr = kernel32.GlobalLock(hglob) ctypes.memmove(ptr, data, len(data)) kernel32.GlobalUnlock(hglob) stream = ctypes.c_void_p() ole32.CreateStreamOnHGlobal(hglob, True, ctypes.byref(stream)) # Load image from stream bitmap = ctypes.c_void_p() status = gdi.GdipCreateBitmapFromStream(stream, ctypes.byref(bitmap)) if status != 0: raise ImageDecodeException("GDI+ probleme sur l'image ") hBitmap = ctypes.c_void_p() result = gdi.GdipCreateHBITMAPFromBitmap(bitmap, ctypes.byref(hBitmap), 0) width = ctypes.c_uint() height = ctypes.c_uint() gdi.GdipGetImageWidth(bitmap, ctypes.byref(width)) gdi.GdipGetImageHeight(bitmap, ctypes.byref(height)) #print "Width", width.value #print "Height", height.value self.image = hBitmap.value win32gui.SendMessage(el.hwnd, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, self.image) el.fichier=fichier self.refresh() gdi.GdipDisposeImage(bitmap) gdi.GdiplusShutdown(token) def changepilimage(self, el, fichier, fonction=None): try: test=PIL except: raise ImportError return el.fichier=fichier el.pilimage = PIL.Image.open(el.fichier) if fonction is not None: el.pilimage=fonction(el.pilimage) dib = PIL.ImageWin.Dib(el.pilimage) hwnd = PIL.ImageWin.HWND(el.hwnd) dib.draw(hwnd, (0,0, el.l,el.h)) def setedittext(self, el, text="AAAA"): ctrl = el.hwnd txt = text.replace("\r\n", "\n") txt = txt.replace("\n", "\r\n") #.encode('cp1252','ignore') result = win32gui.SendMessage(ctrl, win32con.WM_SETTEXT, 0, txt) def _getMultipleWindowValues(self, h, getCountMessage, getValueMessage): result = [] VALUE_LENGTH = 1024 #256 bufferlength_int = struct.pack('i', VALUE_LENGTH) valuecount = win32gui.SendMessage(h, getCountMessage, 0, 0) for itemIndex in range(valuecount): valuebuffer = array.array('c', bufferlength_int + " "*(VALUE_LENGTH - len(bufferlength_int))) valueLength = win32gui.SendMessage(h, getValueMessage, itemIndex, valuebuffer) result.append(valuebuffer.tostring()[:valueLength]) return result def getedittext(self, h): try: vret=self._getMultipleWindowValues(h, getCountMessage=win32con.EM_GETLINECOUNT, getValueMessage=win32con.EM_GETLINE) except: vret=[None] return vret def gettext(self, el): ctrl = el.hwnd buf_size = 1 + win32gui.SendMessage(ctrl, win32con.WM_GETTEXTLENGTH, 0, 0) buffer = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(ctrl, win32con.WM_GETTEXT, buf_size, buffer) return buffer[:buf_size] def refresh(self): win32gui.UpdateWindow(self.hwnd) self.visible(False) self.visible() ###win32gui.PumpWaitingMessages() time.sleep(0.01) #win32gui.MoveWindow(el.hwnd, el.x,el.y,el.l,el.h, 1) #win32gui.InvalidateRect(self.hwnd,None,True) #win32gui.SendMessage(self.hwnd, win32con.WM_REDRAW,1,0) #win32gui.SendMessage(self.hwnd, commctrl.LVM_UPDATE,1,0) def pumpw(self): win32gui.PumpWaitingMessages() def color(self,r=0,v=0,b=0): return int(win32api.RGB(r,v,b)) def transparence(self,color=-128): #int(win32api.RGB(255,0,0))): """ si color<0 transparence de fenêtre (entre -1 et -256 pour 0 à 255) si color>0 transparence de couleur exemple1 : w.transparence(color=w.color(255,0,0)) exemple2 : w.transparence(color=-128) """ if color<0: s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s| win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(self.hwnd, 0, -1-color, win32con.LWA_ALPHA) else: s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s|win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(self.hwnd, color,0, win32con.LWA_COLORKEY) def atest(self): # ne fonctionne pas... s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) print 3185,win32con.WS_CAPTION, 0xFFFFFF-win32con.WS_CAPTION print 3186,win32con.WS_BORDER,0x800000 style = win32con.WS_VISIBLE style |= win32con.DS_MODALFRAME style |= win32con.DS_SETFOREGROUND style |= win32con.WS_THICKFRAME style |= win32con.WS_CAPTION style |= win32con.WS_SYSMENU style |= win32con.WS_MINIMIZEBOX style |= win32con.WS_MAXIMIZEBOX style |= win32con.WS_BORDER style |= win32con.WS_CHILD style |= win32con.WS_POPUP # | self.style_MINIMIZEBOX | self.style_MAXIMIZEBOX win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, style) win32gui.MoveWindow(self.hwnd, 30,10, self.l+120,self.h+80, 1) self.refresh() def settitre(self, mode='REMOVE'): if mode=='REMOVE': s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s|0x00C00000) else: s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s|0x00C00000) def htmlmanaged(self, purl=None, x=0,y=0, l=None,h=None, valideactivex=False, prepare=0): if purl is None: purl=os.getcwd().replace('\\','/')+"/vide.htm" if purl.startswith("file:") or purl.startswith("http:"): url=purl else: url="file:///"+purl url=url.replace('\\/','/') url=url.replace('\\','/') if not url.endswith("/"): url+="/" if l is None: l=self.l if h is None: h=self.h-22-8-8 #alert(url,purl) def hvalideactivex(duree=1): import win32gui,win32con,time hvalideactivex.pid=[] def cherchetitre(h, titre="ink.htm"): #if not win32gui.IsWindowVisible(h): # return txt=win32gui.GetWindowText(h) if txt.find(titre)>-1: tid,pid=win32process.GetWindowThreadProcessId(h) hvalideactivex.pid.append(pid) while hvalideactivex.pid==[]: time.sleep(0.05) win32gui.EnumWindows(cherchetitre, u"ink.htm") self.htmlmanagedpid=hvalideactivex.pid hvalideactivex.htrouve=None def traitefenetres(h, titre=""): if win32gui.IsWindowVisible(h): tid,pid=win32process.GetWindowThreadProcessId(h) if pid in hvalideactivex.pid: txt=win32gui.GetWindowText(h).lower() if txt=="internet explorer": hvalideactivex.htrouve=h """ if not win32gui.IsWindowVisible(h): return txt=win32gui.GetWindowText(h) if txt.find("Internet")>-1: tid,pid=win32process.GetWindowThreadProcessId(h) print 2088,txt,' pid',pid,hvalideactivex.pid if txt=="Internet Explorer": iex,iey,iel,ieh=win32gui.GetWindowRect(h) if iex>300: time.sleep(0.05) hvalideactivex.htrouve=h """ for i in range(duree*9): #print i, win32gui.EnumWindows(traitefenetres, u"Titre") if hvalideactivex.htrouve is not None: #win32gui.SetActiveWindow(hvalideactivex.htrouve) #time.sleep(0.01) #win32gui.SetForegroundWindow(hvalideactivex.htrouve) #time.sleep(0.05) x,y,l,h = win32gui.GetWindowRect(hvalideactivex.htrouve) #print 89,x,y,l,h,win32gui.GetWindowText(hvalideactivex.htrouve) win32gui.MoveWindow(hvalideactivex.htrouve, 0,0, l-x,h-y,1 ) time.sleep(0.05) win32gui.ShowWindow(hvalideactivex.htrouve, win32con.SW_SHOWNORMAL) time.sleep(0.05) win32gui.SetForegroundWindow(hvalideactivex.htrouve) time.sleep(0.1) keyvkcode("VK_LEFT") time.sleep(0.50) keyvkcode("VK_RETURN") time.sleep(0.1) #keyvkcode("VK_SPACE") #time.sleep(0.01) return time.sleep(0.1) def hictrlactivex(w): time.sleep(0.250) #time.sleep(1) hvalideactivex(8) #hvalideactivex(1) if prepare<2: #os.system("taskkill /F /IM iexplore.exe") # 'tue' tous les Internet-explorer #time.sleep(0.05) #alert("920",purl) ''' import win32process StartupInfo = win32process.STARTUPINFO() StartupInfo.dwFlags #StartupInfo.dwFlags = win32process.STARTF_USESHOWWINDOW hp, ht, pid, tid = win32process.CreateProcess(None, "'''+os.path.expandvars("%ProgramFiles%")+'''\\iexplore.exe" -k '+os.getcwd()+'\\the.htm', None, None, # must inherit handles to pass std # handles 1, 0, None, None, #directory StartupInfo) ''' #os.system('start "" /MIN "'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url) """ info = subprocess.STARTUPINFO() info.dwFlags = 1 info.wShowWindow = 2 #2=minimized tie=subprocess.Popen('"'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url, startupinfo=info) time.sleep(0.250) """ info = win32process.STARTUPINFO() info.dwFlags=1 info.wShowWindow=2 hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, '"'+pfdir32+'\\Internet Explorer\\iexplore.exe" -k '+url, None, None, 1, win32process.NORMAL_PRIORITY_CLASS, None, None, plance_info) time.sleep(0.250) # print 2914,tie.pid ; pas le bon PID ?????????? if prepare==1: return time.sleep(0.025) if url.startswith("http"): time.sleep(0.1) urlsearch=url if url.startswith("http://"): urlsearch=url[7:-1] if url.startswith("file:///"): urlsearch=url[10:-1] #url[8:-1] titresearch=urlsearch.replace('/','\\') else: titresearch=urlsearch titresearch="Google" #alert(urlsearch) #print 2056,urlsearch self.navig=IEpilot(attendurl=urlsearch) if valideactivex: hictrlactivex(None) nb=300 titresearch = titresearch.lower() self.ffille=False while True: time.sleep(0.01) nb-=1 if nb<0: break try: #self.ffille = win32gui.FindWindowEx(0,0,0,'Google - Windows Internet Explorer') def traitehandle(h, rlist): txt = win32gui.GetWindowText(h).lower() if txt.find(titresearch)>-1: #if txt.find("Internet")>-1 or txt.find("IE")>-1: if txt.find("internet")>-1 or txt.find("ie")>-1: #print 2271,txt rlist.append(h) #return False rlist=[] win32gui.EnumWindows(traitehandle, rlist) if len(rlist)>0: #kiosk est positionné à (-32000,-32000) ; Attn: seulement la 1ère instance d'un kiosk for hfind in rlist: #print 3359,win32gui.GetWindowText(hfind) hrect=win32gui.GetWindowRect(hfind) #print 3361,hrect if hrect[0]<-30000: self.ffille=hfind break if self.ffille==False: #la 2ème instance de kiosk est positionné à (0,0,largeurécran,hauteurécran) for hfind in rlist: #print 2972,win32gui.GetWindowRect(hfind) hrect=win32gui.GetWindowRect(hfind) if hrect[0]==0 and hrect[1]==0 and hrect[2]==metric.SM_CXSCREEN and hrect[3]==metric.SM_CYSCREEN: self.ffille=hfind break if self.ffille: break except win32gui.error: print 'fille not found (2967)' return if self.ffille: break #print 3384,self.ffille if self.ffille: #sm = ctypes.windll.user32.GetSystemMenu(self.ffille, 0) #num = ctypes.windll.user32.GetMenuItemCount(sm) #for i in range(num,0,-1): # result = ctypes.windll.user32.RemoveMenu(sm, i-1, win32con.MF_BYPOSITION | win32con.MF_REMOVE) #ctypes.windll.user32.DrawMenuBar(self.ffille) ###win32gui.MoveWindow(self.ffille, x,y, l, h-40, 0) #self.origparent=ctypes.windll.user32.SetParent(self.ffille, self.hwnd) self.origparent=win32gui.SetParent(self.ffille, self.hwnd) time.sleep(0.01) #print win32gui.GetParent(self.ffille),self.origparent win32gui.MoveWindow(self.ffille, x,y, l,h, 1) time.sleep(0.01) #print win32gui.GetWindowRect(self.ffille),h,self.h else: print 'fille not found (3002)' return """ def lfwindows(hw, hlist): #liste les fenêtres filles d'une fenêtre text = win32gui.GetWindowText(hw) if text != "": hlist.append([hw,text]) print 2578,hw,"\tfenêtre fille",text text = win32gui.GetWindowText(self.hwnd) print "Fenetre parent:",text print "Fille traitee:",self.ffille hfilleslist=[] win32gui.EnumChildWindows(self.hwnd, lfwindows, hfilleslist) """ #time.sleep(0.1) #win32gui.MoveWindow(self.ffille, x,y, l,h, 0) #time.sleep(0.1) #win32gui.PumpWaitingMessages() #self.refresh() #self.navig.navigUrl(url) """ if valideactivex: print 2188 hvalideactivex(0) """ #print 2189 return self.navig def htmlisole(self, x,y,l,h, fichier="", valideactivex=False, retard=0.250): def hvalideactivex(duree=1): import win32gui,win32con,time hvalideactivex.htrouve=None def traitefenetres(h, titre=""): txt=win32gui.GetWindowText(h) if txt.find("Avertissement")>-1 and txt.find("Windows")>-1: time.sleep(0.05) #win32gui.SetForegroundWindow(h) hvalideactivex.htrouve=h for i in range(duree*9): time.sleep(0.1) win32gui.EnumWindows(traitefenetres, u"Titre") if hvalideactivex.htrouve is not None: #win32gui.SetForegroundWindow(hvalideactivex.htrouve) #time.sleep(0.01) #win32gui.SetActiveWindow(hvalideactivex.htrouve) #time.sleep(0.01) """ x,y,l,h = win32gui.GetWindowRect(hvalideactivex.htrouve) #print 89,x,y,l,h,win32gui.GetWindowText(hvalideactivex.htrouve) win32gui.MoveWindow(hvalideactivex.htrouve, 0,0, l-x,h-y,1 ) time.sleep(0.01) win32gui.ShowWindow(hvalideactivex.htrouve, win32con.SW_SHOWNORMAL) time.sleep(0.01) win32gui.SetForegroundWindow(hvalideactivex.htrouve) """ time.sleep(1.1) keyvkcode("VK_LEFT") time.sleep(0.50) keyvkcode("VK_RETURN") time.sleep(1.1) #keyvkcode("VK_SPACE") #time.sleep(0.05) return def hictrlactivex(w): time.sleep(0.1) hvalideactivex(8) #hvalideactivex(1) x=-2500 source=""" """ #left:100px; #os.system("taskkill /F /IM mshta.exe") open(os.getcwd()+"\\temp.hta","w").write(source) #os.startfile(os.getcwd()+"\\temp.hta") time.sleep(0.01) #os.system('start "" /LOW "'+os.getcwd()+"\\temp.hta"+'"') #os.system('start "" /MIN "'+os.getcwd()+"\\temp.hta"+'"') """ info = subprocess.STARTUPINFO() #info.dwFlags = 1 info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = 2 #2=minimized #info.wShowWindow = subprocess.SW_HIDE subprocess.Popen('C:\\windows\\system32\\mshta.exe '+os.getcwd()+"\\temp.hta", startupinfo=info) """ info = win32process.STARTUPINFO() info.dwFlags=1 info.wShowWindow=2 hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, 'C:\\windows\\system32\\mshta.exe '+os.getcwd()+"\\temp.hta", None, None, 1, win32process.NORMAL_PRIORITY_CLASS, None, None, plance_info) time.sleep(retard) if valideactivex: hictrlactivex(None) def traitehandle(h, rlist): if len(rlist)==0: txt=win32gui.GetWindowText(h) if txt.find("temp.hta")>-1: #print txt #print os.getcwd()+"\\temp.hta" #print rlist.append(h) #return False self.ffille=False nb=200 #time.sleep(0.250) while True: time.sleep(0.01) nb-=1 if nb<0: break try: """ h = win32gui.FindWindowEx(0,0,0,os.getcwd()+"\\temp.hta") if h!=0: self.ffille = h break """ rlist=[] win32gui.EnumWindows(traitehandle, rlist) if len(rlist)>0: self.ffille=rlist[0] break except win32gui.error: print 'not found' #print 3189,200-nb," /100e sec" #print 2969,nb if self.ffille: self.origparent=ctypes.windll.user32.SetParent(self.ffille, self.hwnd) time.sleep(0.01) win32gui.MoveWindow(self.ffille, x,y, l,h, 0) time.sleep(0.01) #self.active() #win32gui.RedrawWindow(self.hwnd,(self.x,self.y,self.l,self.h),None,0) #win32gui.InvalidateRect(self.hwnd,None,True) #win32gui.SendMessage(self.hwnd, win32con.WM_REDRAW,1,0) #win32gui.SendMessage(self.hwnd, commctrl.LVM_UPDATE,1,0) def lanceincruste(self, x=200,y=40,l=800,h=600, commande="", params="", titre=""): #os.startfile(commande) try: #p = subprocess.Popen(commande, shell=False) os.system('start "" "'+commande+'" '+params) #True, stdout=subprocess.PIPE) #p.wait() time.sleep(0.1) #result=p.stdout.read().decode('cp850','replace') except: alert("impossible de lancer l'application") return self.ffille=False nb=50 while True: time.sleep(0.1) nb-=1 if nb<0: break try: #self.ffille = win32gui.FindWindowEx(0,0,0,os.getcwd()+"\\temp.hta") def traitehandle(h, rlist): txt=win32gui.GetWindowText(h) if txt.find(titre)>-1: rlist.append(h) #return False rlist=[] win32gui.EnumWindows(traitehandle, rlist) if len(rlist)>0: self.ffille=rlist[0] break except win32gui.error: print 'not found' #print 5235,"*"*55 if self.ffille: #keyd(win32con.VK_F11) self.origparent=ctypes.windll.user32.SetParent(self.ffille, self.hwnd) time.sleep(0.01) ##win32gui.MoveWindow(self.ffille, x,y, l, h, 0) ##time.sleep(0.1) #win32gui.SendMessage(self.ffille, win32con.WM_SYSCOMMAND, win32con.SC_MAXIMIZE, 0) #time.sleep(0.01) win32gui.MoveWindow(self.ffille, x,y, l, h, 0) time.sleep(0.01) #keyd(win32con.VK_F11) #print 2169,self.origparent def changelargeur(self, el, col,largeur): win32gui.SendMessage(el.hwnd, commctrl.LVM_SETCOLUMNWIDTH, col, largeur) def changealign(self,el,col,align="LEFT"): #temp = win32gui.SendMessage(el.hwnd, commctrl.LVM_GETCOLUMN, 4) if el.hwnd is not None: lvc = win.LVCOLUMN(mask = commctrl.LVCF_FMT) if align=='RIGHT': lvc.fmt = commctrl.LVCFMT_RIGHT elif align=='CENTER': lvc.fmt = commctrl.LVCFMT_CENTER else: lvc.fmt = commctrl.LVCFMT_LEFT win32gui.SendMessage(el.hwnd, commctrl.LVM_SETCOLUMN, col, lvc.toparam()) self.changelargeur(el, col, 10) self.changelargeur(el, col, el.collarg[col]) def autotaille(self, el): import types lmax=[1]*len(el.ldata[0]) for l in el.ldata: for n,i in enumerate(l): if isinstance(i, (basestring,unicode)): long=len(i) else: long=len(repr(i)) if lmax[n]0 vers le haut, <0 vers le bas) """ result = win32gui.SendMessage(el.hwnd, commctrl.LVM_SCROLL, 0, nb) def listecoches(self, el): """ retourne deux listes 1) un item pour chaque ligne ; True si coché, False si non-coché 2) liste des seuls éléments cochés """ hwnd=el.hwnd GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx OpenProcess = ctypes.windll.kernel32.OpenProcess WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory memcpy = ctypes.cdll.msvcrt.memcpy # Allocate virtual memory inside target process pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(win32con.PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0]) pLVI = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) # Prepare an LVITEM record and write it to target process memory colonne=0 lvitem_str = struct.pack('iiiiiiiii', *[0,0,colonne,0,0,pBuffer,4096,0,0]) lvitem_buffer = ctypes.create_string_buffer(lvitem_str) copied = ctypes.create_string_buffer(4) p_copied = ctypes.addressof(copied) WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) # iterate items in the SysListView32 control num_items = win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMCOUNT) item_texts = [] liste_coches=[] for ligne in range(num_items): LVIS_STATEIMAGEMASK = 61440 state=win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMSTATE, ligne, LVIS_STATEIMAGEMASK) etat=(state & 0x2000 == 0x2000) item_texts.append(etat) if etat: liste_coches.append(ligne) VirtualFreeEx(hProcHnd, pBuffer, 0, win32con.MEM_RELEASE) VirtualFreeEx(hProcHnd, pLVI, 0, win32con.MEM_RELEASE) win32api.CloseHandle(hProcHnd) return(item_texts,liste_coches) def lvreadligcol(self, el, ligne=0, colonne=1): hwnd=el.hwnd GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx OpenProcess = ctypes.windll.kernel32.OpenProcess WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory memcpy = ctypes.cdll.msvcrt.memcpy # Allocate virtual memory inside target process pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(win32con.PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0]) pLVI = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) # Prepare an LVITEM record and write it to target process memory lvitem_str = struct.pack('iiiiiiiii', *[0,0, colonne,0,0,pBuffer,4096,0,0]) lvitem_buffer = ctypes.create_string_buffer(lvitem_str) copied = ctypes.create_string_buffer(4) p_copied = ctypes.addressof(copied) WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) #num_items = win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMCOUNT) #---pour une ligne----------------- win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMTEXT, ligne, pLVI) target_buff = ctypes.create_string_buffer(4096) ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied) #---pour une ligne----------------- VirtualFreeEx(hProcHnd, pBuffer, 0, win32con.MEM_RELEASE) VirtualFreeEx(hProcHnd, pLVI, 0, win32con.MEM_RELEASE) win32api.CloseHandle(hProcHnd) return target_buff.value def lvgetposition(self, el, ligne=0): """ Retourne la position X,Y de la ligne (n°) passée en paramètre Position en pixels, relativement à l'objet ListView position du coin haut gauche. """ class LVPOINT(ctypes.Structure): _fields_=[('x', ctypes.c_long),('y', ctypes.c_long)] toto=LVPOINT() temp = win32gui.SendMessage(el.hwnd, commctrl.LVM_GETITEMPOSITION, ligne, toto) return(toto.x,toto.y) def lvgetrect(self, el, ligne=0): """ Retourne le rectangle X,Y,XX,YY de la ligne (n°) passée en paramètre Position en pixels, relativement à l'objet ListView position du coin haut gauche. """ class RECT(ctypes.Structure): _fields_=[('Left', ctypes.c_long),('Top', ctypes.c_long),('Right', ctypes.c_long),('Bottom', ctypes.c_long)] buf=RECT() buf.Left=commctrl.LVIR_BOUNDS temp = win32gui.SendMessage(el.hwnd, commctrl.LVM_GETITEMRECT, ligne, buf) return(buf.Left,buf.Top,buf.Right,buf.Bottom) def lvgetcellrect(self, el, ligne=0, col=0): """ Retourne le rectangle X,Y,XX,YY de la cellule de la ligne passés en paramètres Position en pixels, relativement à l'objet ListView position du coin haut gauche. """ class RECT(ctypes.Structure): _fields_=[('Left', ctypes.c_long),('Top', ctypes.c_long),('Right', ctypes.c_long),('Bottom', ctypes.c_long)] buf=RECT() buf.Left=commctrl.LVIR_BOUNDS temp = win32gui.SendMessage(el.hwnd, commctrl.LVM_GETITEMRECT, ligne, buf) xc=0 for i in range(col): xc += el.collarg[i] return(buf.Left+xc,buf.Top, buf.Left+xc+el.collarg[col],buf.Bottom) def ClearListItems(self, el): win32gui.SendMessage(el.hwnd, commctrl.LVM_DELETEALLITEMS) def setcellule(self, el, lig, col, data=None): """ Remplit le contenu de la cellule (lig,col) avec data """ el.item.iItem = lig el.item.iSubItem = col el.item.text=forme(data,el.formats[col]) el.item.iImage=-1 try: win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEM, 0, el.item.toparam()) except: pass def modiflig(self, el, num, *data): """ Remplace le contenu de la ligne num avec *data """ el.item.text=forme(data[0],el.formats[0]) el.item.iItem = num el.item.iSubItem=0 numimage=None if el.listimage: if el.fimage is None: numimage=0 else: numimage=el.fimage(num,el) if el.colimage==0: el.item.iImage=numimage else: el.item.iImage=-1 else: el.item.iImage=-1 ###result = win32gui.SendMessage(el.hwnd, commctrl.LVM_INSERTITEM, 0, el.item.toparam()) for col_no,col in enumerate(data[1:]): el.item.iSubItem = col_no+1 if el.listimage: if el.colimage==col_no+1: el.item.iImage=numimage else: el.item.iImage=-1 el.item.text=forme(col,el.formats[col_no+1]) try: win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEM, 0, el.item.toparam()) except: pass def AddListItem(self, el, num, *data): #el.item.text=str(data[0]) el.item.text=forme(data[0],el.formats[0]) el.item.iItem = num el.item.iSubItem=0 numimage=None if el.listimage: if el.fimage is None: numimage=0 else: numimage=el.fimage(num,el) if el.colimage==0: el.item.iImage=numimage else: el.item.iImage=-1 else: el.item.iImage=-1 result = win32gui.SendMessage(el.hwnd, commctrl.LVM_INSERTITEM, 0, el.item.toparam()) for col_no,col in enumerate(data[1:]): el.item.iSubItem = col_no+1 if el.listimage: if el.colimage==col_no+1: el.item.iImage=numimage else: el.item.iImage=-1 el.item.text=forme(col,el.formats[col_no+1]) try: win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEM, 0, el.item.toparam()) except: pass def visulliste_OLD(self, el): win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,1,0) win32gui.SendMessage(el.hwnd, commctrl.LVM_DELETEALLITEMS) el.item = win.LVITEM(iItem = 0) num_items = win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEMCOUNT,len(el.ldata), commctrl.LVSICF_NOINVALIDATEALL | commctrl.LVSICF_NOSCROLL) num=0 if len(el.ldata)>100: for l in el.ldata[:75]: self.AddListItem(el, num, *l) num+=1 time.sleep(0.01) win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,1,0) win32gui.PumpWaitingMessages() #self.refresh() win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,0,0) #time.sleep(0.01) for l in el.ldata[75:]: self.AddListItem(el, num, *l) num+=1 win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,1,0) else: win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,0,0) for l in el.ldata: self.AddListItem(el, num, *l) num+=1 win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,1,0) def visulliste_0(self, el): win32gui.SendMessage(el.hwnd, commctrl.LVM_DELETEALLITEMS) el.item = win.LVITEM(iItem = 0) num_items = win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEMCOUNT,len(el.ldata), commctrl.LVSICF_NOINVALIDATEALL | commctrl.LVSICF_NOSCROLL) win32gui.PostMessage(self.hwnd, win32con.WM_SETREDRAW,True,0) num=0 if len(el.ldata)>100: for l in el.ldata[:50]: self.AddListItem(el, num, *l) num+=1 #win32gui.PumpWaitingMessages() #self.refresh() win32gui.PumpWaitingMessages() #win32gui.PostMessage(self.hwnd, win32con.WM_SETREDRAW,False,0) for l in el.ldata[50:]: self.AddListItem(el, num, *l) num+=1 #win32gui.PumpWaitingMessages() win32gui.PostMessage(self.hwnd, win32con.WM_SETREDRAW,True,0) #win32gui.PumpWaitingMessages() else: win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,False,0) for l in el.ldata: self.AddListItem(el, num, *l) num+=1 #win32gui.PumpWaitingMessages() #time.sleep(0.01) win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,True,0) #win32gui.PumpWaitingMessages() def visulliste(self, el): win32gui.SendMessage(el.hwnd, commctrl.LVM_DELETEALLITEMS) el.item = win.LVITEM(iItem = 0) num_items = win32gui.SendMessage(el.hwnd, commctrl.LVM_SETITEMCOUNT,len(el.ldata), commctrl.LVSICF_NOINVALIDATEALL | commctrl.LVSICF_NOSCROLL) win32gui.PostMessage(self.hwnd, win32con.WM_SETREDRAW,True,0) num=0 win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,False,0) win32gui.PumpWaitingMessages() for l in el.ldata: self.AddListItem(el, num, *l) num+=1 if num==50: win32gui.PumpWaitingMessages() win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,True,0) win32gui.PumpWaitingMessages() win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,False,0) win32gui.PumpWaitingMessages() win32gui.PostMessage(el.hwnd, win32con.WM_SETREDRAW,True,0) #win32gui.PumpWaitingMessages() def ajoutligne(self, el, lcontenu): el.ldata.append(lcontenu) self.visulliste(el) def emptylliste(self, el): result = win32gui.SendMessage(el.hwnd, commctrl.LVM_DELETEALLITEMS) def replacelliste(self, el, lliste): el.ldata=lliste self.emptylliste(el) self.visulliste(el) def premajtext(self, el, txt): # met à jour un label, sans redessiner la fenêtre try: if txt != el.texte: el.texte=txt return 1 except: pass return 0 def majtextseul(self, el, txt): # met à jour un label, et redessine juste le label, si nécessaire try: if txt != el.texte: el.texte=txt win32gui.InvalidateRect(self.hwnd, el.rect, True) #win32gui.RedrawWindow(self.hwnd, el.rect, None, win32con.RDW_ERASE+win32con.RDW_INVALIDATE) #win32gui.PumpWaitingMessages() return 1 except: pass return 0 def majtext(self, el, txt): # met à jour un label, et redessine la fenêtre si nécessaire try: if txt != el.texte: el.texte=txt win32gui.InvalidateRect(self.hwnd,None,True) #win32gui.PumpWaitingMessages() return 1 except: pass return 0 def redessine(self): try: win32gui.InvalidateRect(self.hwnd,None,True) #win32gui.PumpWaitingMessages() except: pass def colorlabel(self, hwnd, msg, wparam, lparam): pass return #brush=win32gui.GetStockObject(win32con.WHITE_BRUSH) """ win32gui.SetBkColor(wparam, win32api.RGB(230,230,255)) win32gui.SetTextColor(wparam, win32api.RGB(0,192,0)) win32gui.SetBkMode(wparam, win32con.OPAQUE) #br = win32gui.CreateSolidBrush(win32api.RGB(0,0,0)) """ def colorchamp(self, hwnd, msg, wparam, lparam): win32gui.SetBkColor(wparam, win32api.RGB(255,255,255)) win32gui.SetTextColor(wparam, win32api.RGB(0,0,0)) win32gui.SetBkMode(wparam, win32con.OPAQUE) #win32gui.SetBkMode(wparam, win32con.TRANSPARENT) def OnPaint(self, hwnd, msg, wparam, lparam): if self.hwnd is None: self.hwnd = hwnd #if self.hDC is not None: # return self.hDC, self.paintStruct = win32gui.BeginPaint(hwnd) if self.fond is not None: win32gui.SetGraphicsMode(self.hDC, win32con.GM_ADVANCED) cpen = win32gui.CreatePen(5, 0, win32api.RGB(255,255,255)) win32gui.SelectObject(self.hDC, cpen) if len(self.fond)>5: gradient="""( {'x':0, 'y':0, 'Red':"""+str(self.fond[0]*256)+""", 'Green':"""+str(self.fond[1]*256)+""", 'Blue':"""+str(self.fond[2]*256)+""", 'Alpha':0}, {'x':"""+str(self.l)+""", 'y':"""+str(self.h)+""", 'Red':"""+str(self.fond[3]*256)+""", 'Green':"""+str(self.fond[4]*256)+""", 'Blue':"""+str(self.fond[5]*256)+""", 'Alpha':0}, )""" coins=eval(gradient) mesh=((0,1),) win32gui.GradientFill(self.hDC, coins, mesh, win32con.GRADIENT_FILL_RECT_V) else: if self.fond==-1: brush=win32gui.CreateSolidBrush(win32api.RGB(255,255,255)) win32gui.SelectObject(self.hDC, brush) win32gui.Rectangle(self.hDC, 0,0, 20,20) else: brush=win32gui.CreateSolidBrush(win32api.RGB(*self.fond)) win32gui.SelectObject(self.hDC, brush) win32gui.Rectangle(self.hDC, 0,0, self.l,self.h) if len(self.ldessins)>0 or len(self.limages)>0 or len(self.lpilimages)>0 or len(self.ltexts)>0 or len(self.lvlists)>0 or len(self.larbres)>0 or len(self.lmonths)>0 : for e in self.ldessins: el=self.dessins[e] win32gui.SetGraphicsMode(self.hDC, win32con.GM_ADVANCED) dess=el.dessin.split('\n') dmode="" color=None pen=None for lig in dess: if len(lig)>2: l=lig.rstrip().lstrip() d=l.split(' ') cde=d[0].upper() par=[int(i) for i in d[1:]] if dmode=="MULTILINE": if cde=="ENDMULTILINE": dmode="" cde="" win32gui.EndPath(self.hDC) win32gui.StrokeAndFillPath(self.hDC) else: par=[int(i) for i in d] win32gui.LineTo(self.hDC, *par) cde="" elif cde=="ABRUSH": brush=win32gui.CreateSolidBrush(0XDDEEEEFF) win32gui.SelectObject(self.hDC, brush) elif cde=="BRUSH": brush=win32gui.CreateSolidBrush(win32api.RGB(*par)) win32gui.SelectObject(self.hDC, brush) elif cde=="MOVETO": win32gui.MoveToEx(self.hDC,*par) elif cde=="MULTILINE": dmode="MULTILINE" win32gui.BeginPath(self.hDC) elif cde=="COLOR": color=win32api.RGB(*par) elif cde=="PEN": cpen = win32gui.CreatePen(par[0], par[1], color) win32gui.SelectObject(self.hDC, cpen) elif cde=="LINETO": win32gui.LineTo(self.hDC, *par) elif cde=="RECTANGLE": win32gui.Rectangle(self.hDC, *par) pass elif cde=="GRADIENT": gpar=par elif cde=="TRIANGLEG": gradient="""( {'x':"""+d[1]+""", 'y':"""+d[2]+""", 'Red':"""+str(gpar[0]*256)+""", 'Green':"""+str(gpar[1]*256)+""", 'Blue':"""+str(gpar[2]*256)+""", 'Alpha':0}, {'x':"""+d[3]+""", 'y':"""+d[4]+""", 'Red':"""+str(gpar[3]*256)+""", 'Green':"""+str(gpar[4]*256)+""", 'Blue':"""+str(gpar[5]*256)+""", 'Alpha':0}, {'x':"""+d[5]+""", 'y':"""+d[6]+""", 'Red':"""+str(gpar[6]*256)+""", 'Green':"""+str(gpar[7]*256)+""", 'Blue':"""+str(gpar[8]*256)+""", 'Alpha':0}, )""" coins=eval(gradient) mesh=((0,1,2),) win32gui.GradientFill(self.hDC, coins, mesh, win32con.GRADIENT_FILL_TRIANGLE) elif cde=="RECTANGLEH": gradient="""( {'x':"""+d[1]+""", 'y':"""+d[2]+""", 'Red':"""+str(gpar[0]*256)+""", 'Green':"""+str(gpar[1]*256)+""", 'Blue':"""+str(gpar[2]*256)+""", 'Alpha':0}, {'x':"""+d[3]+""", 'y':"""+d[4]+""", 'Red':"""+str(gpar[3]*256)+""", 'Green':"""+str(gpar[4]*256)+""", 'Blue':"""+str(gpar[5]*256)+""", 'Alpha':0}, )""" coins=eval(gradient) mesh=((0,1),) win32gui.GradientFill(self.hDC, coins, mesh, win32con.GRADIENT_FILL_RECT_H) elif cde=="RECTANGLEV": gradient="""( {'x':"""+d[1]+""", 'y':"""+d[2]+""", 'Red':"""+str(gpar[0]*256)+""", 'Green':"""+str(gpar[1]*256)+""", 'Blue':"""+str(gpar[2]*256)+""", 'Alpha':0}, {'x':"""+d[3]+""", 'y':"""+d[4]+""", 'Red':"""+str(gpar[3]*256)+""", 'Green':"""+str(gpar[4]*256)+""", 'Blue':"""+str(gpar[5]*256)+""", 'Alpha':0}, )""" coins=eval(gradient) mesh=((0,1),) win32gui.GradientFill(self.hDC, coins, mesh, win32con.GRADIENT_FILL_RECT_V) s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.SS_BITMAP for e in self.lpilimages: el=self.pilimages[e] if el.fichier!= "": defautpil() el.pilimage = PIL.Image.open(el.fichier) dib = PIL.ImageWin.Dib(el.pilimage) hwnd = PIL.ImageWin.HWND(el.hwnd) #dib.draw(hwnd,(el.x,el.y, el.l+el.x,el.h+el.y)) #avant le 22.02.2012 (= pywin 217 s = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.SS_BITMAP for e in self.limages: import ctypes el=self.images[e] if el.fichier!= "" and hasattr(el,"hwnd"): ext=el.fichier[-3:].upper() if ext=="BMP": #el.image = win32gui.LoadImage(self.hinst, el.fichier, win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE) el.image = win32gui.LoadImage(el.hwnd, el.fichier, win32con.IMAGE_BITMAP, el.x, el.y, win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE) win32gui.SendMessage(el.hwnd, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, el.image) elif ext=="JPG" or ext=="PEG" or ext=="PNG" or ext=="GIF": gdi = ctypes.windll.gdiplus ole32 = ctypes.windll.ole32 kernel32 = ctypes.windll.kernel32 BOOL = ctypes.c_int class GdiplusStartupInput(ctypes.Structure): _fields_ = [ ('GdiplusVersion', ctypes.c_uint32), ('DebugEventCallback', ctypes.c_void_p), ('SuppressBackgroundThread', BOOL), ('SuppressExternalCodecs', BOOL) ] class GdiplusStartupOutput(ctypes.Structure): _fields = [ ('NotificationHookProc', ctypes.c_void_p), ('NotificationUnhookProc', ctypes.c_void_p) ] class CLSID(ctypes.Structure): _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16), ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_uint8 * 8)] def __init__(self, *args): if len(args) == 1: part1, part2, part3, part4, part5 = args[0].split('-') self.Data1 = int(part1, 16) self.Data2 = int(part2, 16) self.Data3 = int(part3, 16) self.Data4[0] = int(part4[0:2], 16) self.Data4[1] = int(part4[2:4], 16) for i in range(6): self.Data4[i+2] = int(part5[i*2:i*2+2], 16) Structure.__init__(self) else: Structure.__init__(self, *args) def __str__(self): return '%08x-%04x-%04x-%s' % (int(self.Data1), int(self.Data2), int(self.Data3), '%02x%02x-%02x%02x%02x%02x%02x%02x' % tuple(self.Data4)) class EncoderParameter(ctypes.Structure): _fields_ = [ ('GUID', CLSID), ('NumberOfValues', ctypes.c_uint32), ('type', ctypes.c_int), #EncoderParameterValueType ('value', ctypes.c_uint32), ] class EncoderParameters(ctypes.Structure): _fields_ = [ ('count', ctypes.c_uint32), ('Parameter', EncoderParameter), ] i = GdiplusStartupInput() o = GdiplusStartupOutput() token = ctypes.c_ulong() i.GdiplusVersion = 1 gdi.GdiplusStartup(ctypes.byref(token), ctypes.byref(i), ctypes.byref(o)) data = open(el.fichier,"rb").read() # Create a HGLOBAL with image data GMEM_MOVEABLE = ctypes.c_int(2) hglob = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data)) ptr = kernel32.GlobalLock(hglob) ctypes.memmove(ptr, data, len(data)) kernel32.GlobalUnlock(hglob) stream = ctypes.c_void_p() ole32.CreateStreamOnHGlobal(hglob, True, ctypes.byref(stream)) # Load image from stream bitmap = ctypes.c_void_p() status = gdi.GdipCreateBitmapFromStream(stream, ctypes.byref(bitmap)) if status != 0: raise ImageDecodeException("GDI+ probleme sur l'image ") hBitmap = ctypes.c_void_p() ''' Alpha, Red, Green, Blue 00 = Lowest Value FF = Highest Value It goes in this order: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F examples: FFFFFFFF is solid white FF000000 is solid black FFFF0000 is solid red FF00FF00 is solid green FF0000FF is solid blue 77000030 would be a transparent dark blue ''' ''' if el.fichier=="fl.png": fondargb = 0xFFFFFFFF else: fondargb = 0x7FFFFFFF ''' ''' color=int(win32api.RGB(r,v,b)) 770000FF bleu transparent ? ou 255 ? s=win32gui.GetWindowLong(self.hwnd,win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, s|win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(self.hwnd, color,0, win32con.LWA_COLORKEY) ou ? SetLayeredWindowAttributes(hWnd, 0, Alpha, LWA_ALPHA) ??? ''' fondargb = 0xFFFFFFFF result = gdi.GdipCreateHBITMAPFromBitmap(bitmap, ctypes.byref(hBitmap), fondargb) ''' print largeur , hauteur width = ctypes.c_uint() height = ctypes.c_uint() gdi.GdipGetImageWidth(bitmap, ctypes.byref(width)) gdi.GdipGetImageHeight(bitmap, ctypes.byref(height)) print "Width", width.value print "Height", height.value #width.value=width.value/2 #ne marche pas #height.value=height.value/2 ''' el.image = hBitmap.value h_image=win32gui.SendMessage(el.hwnd, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, el.image) gdi.GdipDisposeImage(bitmap) #gdi.GdipAddPathRectangle(el.hwnd, 30,10, 300,120) gdi.GdiplusShutdown(token) for e in self.lmonths: el=self.months[e] child_style = win32con.WS_CHILD | win32con.WS_VISIBLE if True: #Border = True child_style |= win32con.WS_BORDER el.l = el.l+2 el.h = el.h+2 el.hwnd = win32gui.CreateWindow("SysMonthCal32", None, child_style, el.x, el.y, el.l, el.h, self.hwnd, 0, self.hinst, None) import ctypes.wintypes class SYSTEMTIME(ctypes.Structure): #Extended, _fields_ = [ ('year', ctypes.wintypes.WORD), ('month', ctypes.wintypes.WORD), ('day_of_week', ctypes.wintypes.WORD), ('day', ctypes.wintypes.WORD), ('hour', ctypes.wintypes.WORD), ('minute', ctypes.wintypes.WORD), ('second', ctypes.wintypes.WORD), ('millisecond', ctypes.wintypes.WORD), ] st = SYSTEMTIME(el.year, el.month, 0, el.day, 0, 0, 0, 0) # positionne le calendrier win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCURSEL, 0, st) # à voir #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCURRENTVIEW, 0, commctrl.MCMV_YEAR) #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCURRENTVIEW, 0, commctrl.MCMV_MONTH) #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCURRENTVIEW, 0, commctrl.MCMV_MONTH) #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCURRENTVIEW, 0, commctrl.MCMV_MONTH) # met (change) la date du jour (le rond rouge) #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETTODAY, 0, st) #nb de mois scrollés par les boutons < et > #win32gui.SendMessage(el.hwnd, commctrl.MCM_SETMONTHDELTA, 3, 0) """ éléments de couleur du mois : win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_BACKGROUND, self.color(255,255,160)) win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_MONTHBK, self.color(160,200,255)) win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_TEXT, self.color(255,0,0)) win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_TITLEBK, self.color(160,0,0)) win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_TITLETEXT, self.color(255,255,0)) win32gui.SendMessage(el.hwnd, commctrl.MCM_SETCOLOR, commctrl.MCSC_TRAILINGTEXT, self.color(255,0,255)) """ for e in self.ltexts: el=self.texts[e] style="" if el.font is not None: win32gui.SelectObject(self.hDC, self.fonts[el.font]) if el.textcolor is not None: win32gui.SetTextColor(self.hDC, win32api.RGB(*el.textcolor)) if el.backcolor is None: win32gui.SetBkMode(self.hDC, win32con.TRANSPARENT) else: win32gui.SetBkMode(self.hDC, win32con.OPAQUE) win32gui.SetBkColor(self.hDC, win32api.RGB(*el.backcolor[:3])) if el.align=='LEFT': style = win32con.DT_LEFT elif el.align=='RIGHT': style = win32con.DT_RIGHT else: style = win32con.DT_CENTER if el.valign=='TOP' or el.valign=='HAUT': style |= win32con.DT_TOP elif el.valign=='BOTTOM' or el.valign=='BAS': style = win32con.DT_BOTTOM else: style = win32con.DT_VCENTER if el.multiligne: pass else: style |= win32con.DT_SINGLELINE # win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER | win32con.DT_TOP | win32con.DT_BOTTOM) if el.texte is not None: el.hDC,el.rect = win32gui.DrawText(self.hDC, el.texte,-1,(el.x,el.y, el.x+el.l,el.y+el.h), style) #win32gui.MoveWindow(el.hwnd, el.x,el.y, el.x+el.l,el.y+el.h, -1) """ for e in self.limages: el=self.images[e] h_image=win32gui.SendMessage(el.hwnd, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, el.image) #self.refresh() win32gui.PumpWaitingMessages() """ for id in self.larbres: el=self.arbres[id] try: temp=el.hwnd win32gui.DestroyWindow(temp) except: pass stylebordure=0 if el.bordure=="CLIENTEDGE": stylebordure |= win32con.WS_EX_CLIENTEDGE if el.bordure=="STATICEDGE": stylebordure |= win32con.WS_EX_STATICEDGE if el.bordure=="WINDOWEDGE": stylebordure |= win32con.WS_EX_WINDOWEDGE if el.bordure=="EDGE_RAISED": stylebordure |= win32con.EDGE_RAISED if el.bordure=="EDGE_SUNKEN": stylebordure |= win32con.EDGE_SUNKEN if el.bordure=="EDGE_BUMP": stylebordure |= win32con.EDGE_BUMP s = win32con.WS_CHILD | win32con.WS_VISIBLE | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS | commctrl.TVS_SHOWSELALWAYS if stylebordure != 0 and stylebordure != win32con.WS_EX_STATICEDGE and stylebordure != win32con.EDGE_RAISED : s |= win32con.WS_BORDER #el.hwnd=win32gui.CreateWindowEx(win32con.WS_EX_CLIENTEDGE, commctrl.WC_TREEVIEW, "arbre", win32con.WS_CHILD | win32con.WS_VISIBLE | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS | commctrl.TVS_SHOWSELALWAYS, el.x,el.y, el.x+el.l,el.y+el.h, self.hwnd, id, self.hinst, None) #el.hwnd=win32gui.CreateWindowEx(win32con.WS_EX_LEFT, commctrl.WC_TREEVIEW, "arbre", win32con.WS_CHILD | win32con.WS_VISIBLE | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS | commctrl.TVS_SHOWSELALWAYS, el.x,el.y, el.l,el.h, self.hwnd, id, self.hinst, None) el.hwnd=win32gui.CreateWindowEx(stylebordure, commctrl.WC_TREEVIEW, "arbre", s, el.x,el.y, el.l,el.h, self.hwnd, id, self.hinst, None) #self.hTreeView=el.hwnd self.allobj[el.hwnd]=el style = win32api.GetWindowLong(el.hwnd, win32con.GWL_STYLE) # pour mettre une case à cocher if el.checkmode: style = style | commctrl.TVS_CHECKBOXES win32api.SetWindowLong(el.hwnd, win32con.GWL_STYLE, style) win32gui.SendMessage(el.hwnd, win32con.WM_SETFONT, self.fonts['TREEDEFAULT'], 0) if el.listimage: # is not None: if self.imageList is None: self.add_listimage(16, None) #limages = win32gui.SendMessage(el.hwnd, commctrl.TVM_SETIMAGELIST, commctrl.TVSIL_NORMAL, self.imageList) limages = win32gui.SendMessage(self.hinst, commctrl.TVM_SETIMAGELIST, commctrl.TVSIL_NORMAL, el.listimage) lnoeuds=[] ordre=-1 for n,noeud in el.arbredata: #print n, noeud.nom, noeud.data, noeud.id, noeud.parent, noeud.idparent flagparent=0 if el.arbredata.nbchild(n)>0: flagparent=1 if noeud.parent is None: hparent=0 else: hparent=el.arbredata.ditems[noeud.parent].handle noeud.idparent=el.arbredata.ditems[noeud.parent].id mask = commctrl.TVIF_HANDLE | commctrl.TVIF_STATE | commctrl.TVIF_TEXT | commctrl.TVIF_IMAGE | commctrl.TVIF_SELECTEDIMAGE | commctrl.TVIS_STATEIMAGEMASK ordre+=1 insert_buf, extras = win.PackTVINSERTSTRUCT(hparent, ordre, (None, noeud.coche, #Checked mask, #style noeud.data.encode('cp1252','ignore'), #texte/contenu noeud.image, #image quand pas focus noeud.image2, #image si focus flagparent, #0=élément simple ; 1=noeud(a des enfants) noeud.id)) noeud.handle = win32gui.SendMessage(el.hwnd, commctrl.TVM_INSERTITEM, 0, insert_buf) self.allobj[noeud.handle]=noeud #print 1870,noeud.nom,noeud.coche #win32gui.SendMessage(el.hwnd, commctrl.TVM_SELECTITEM, commctrl.TVGN_CARET, noeud.handle) if el.arbredata.nbchild(n)>0: lnoeuds.append(noeud.handle) # pour ouvrir tous les noeuds for h in lnoeuds: win32gui.SendMessage(el.hwnd, commctrl.TVM_EXPAND, commctrl.TVE_EXPAND, h) # pour fermer tous les noeuds #for h in lnoeuds: # win32gui.SendMessage(el.hwnd, commctrl.TVM_EXPAND, commctrl.TVE_COLLAPSE, h) # met un "souligné-marque de séparation" # win32gui.SendMessage(el.hwnd, commctrl.TVM_SETINSERTMARK, 0, el.arbredata.ditems[el.arbredata.items[3]].handle) #sélectionne le 1er item ; bof ça marche à moitié, mais c'est indispensable win32gui.SendMessage(el.hwnd, commctrl.TVM_SELECTITEM, commctrl.TVGN_CARET, el.arbredata.ditems[el.arbredata.items[0]].handle) #on coche le 3ème item #win32con.BST_CHECKED BST_INDETERMINATE BST_UNCHECKED #win32gui.SendMessage(el.hwnd, win32con.BM_SETCHECK, win32con.BST_CHECKED, el.arbredata.ditems[el.arbredata.items[3]].handle) # couleur de fond de l'arbre entier win32gui.SendMessage(el.hwnd, commctrl.TVM_SETBKCOLOR, 0, win32api.RGB(*el.fond)) """ # selectionne un item (un seul possible) # 0 au lieu de handle désélectionne win32gui.SendMessage(el.hwnd, commctrl.TVM_SELECTITEM, commctrl.TVGN_CARET, hB) # couleur de fond de l'arbre entier win32gui.SendMessage(el.hwnd, commctrl.TVM_SETBKCOLOR, 0, win32api.RGB(255,255,200)) # couleur du texte de l'arbre entier win32gui.SendMessage(el.hwnd, commctrl.TVM_SETTEXTCOLOR, 0, win32api.RGB(0,0,128)) # marche pas ? win32gui.SendMessage(el.hwnd, commctrl.TVM_SETTOOLTIPS, hB2, "AZERTYUIOP") """ for e in self.lvlists: el=self.vlists[e] #self.visulliste(el) #lig dessous, pour réajuster la taille, si plus petite #win32gui.MoveWindow(el.hwnd, el.x,el.y, el.l,el.h, 1) # la listview win32gui.EndPaint(hwnd, self.paintStruct) def OnInit(self, hwnd, msg, wparam, lparam): if self.hwnd is None: self.hwnd = hwnd win32gui.MoveWindow(hwnd, self.x,self.y, self.l,self.h, 0) for b in self.lbuttons: bt=self.buttons[b] ctrl = win32gui.GetDlgItem(self.hwnd, bt.id) win32gui.MoveWindow(ctrl, bt.x,bt.y,bt.l,bt.h, 1) for e in self.ledits: el=self.edits[e] ctrl = win32gui.GetDlgItem(self.hwnd, el.id) win32gui.MoveWindow(ctrl, el.x,el.y,el.l,el.h, 1) for e in self.llabels: el=self.labels[e] ctrl = win32gui.GetDlgItem(self.hwnd, el.id) win32gui.MoveWindow(ctrl, el.x,el.y,el.l,el.h, 1) def callmenu(self): self.etat="MENU" #print self.hmenu, self.x, self.y if self.hwnd == win32gui.GetForegroundWindow(): x,y,l,h = win32gui.GetWindowRect(self.hwnd) rmenu=win32gui.TrackPopupMenu(self.hmenu, win32con.TPM_LEFTALIGN, x+30, y+40, 0, self.hwnd, None) self.etat=time.time() #print 2291,"ligne de menu :",rmenu,self.titre #win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) def TEST(self, hwnd, msg, wparam, lparam): # pour TEST pass ''' print "-"*66 print 4906,wparam,"TEST" print "-"*66 ''' def OnKeyD(self, hwnd, msg, wparam, lparam): # appelé uniquement dans une fenêtre (pas console) # print 6316,wparam global globalkeyflag k=wparam korig=k if k>=97 and k<97+26: k-=32 """ print print 6368,k,korig,type(k),time.time() for i in self.grainkey: print 6358,i,type(i) print " \t \t ",k in self.grainkey """ if self.hwnd == win32gui.GetForegroundWindow(): if k==win32con.VK_RETURN: globalkeyflag=win32con.VK_RETURN return if k==win32con.VK_ESCAPE: globalkeyflag=win32con.VK_ESCAPE return if k in self.grainkey: globalkeyflag=k return """ try: aaa=self.grainkey[k](self,"window",'KEY_') print 6406 if aaa or aaa is None: if k not in (win32con.VK_UP, win32con.VK_DOWN, win32con.VK_NEXT, win32con.VK_PRIOR, win32con.VK_END): ktime=time.time() msg = MSG() while (time.time()-ktime)<0.05: if win32api.GetAsyncKeyState(korig) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break return except: pass """ try: if pwg_hotkey is not None: for n,hk in enumerate(pwg_hotkey.defhotkeys): if wparam==hk[1]: if pwg_hotkey.func[n] is not None: pwg_hotkey.func[n](wparam) #time.sleep(0.01) except: pass def OnKey(self, hwnd, msg, wparam, lparam): # attention, la touche est déjà passée au système... # (sauf si "Hotkey") # wparam contient le code de la touche. #print 6411,"touche",wparam,"OnKey" global globalkeyflag k=wparam if self.hwnd == win32gui.GetForegroundWindow(): if k==win32con.VK_RETURN: #globalkeyflag=win32con.VK_RETURN #time.sleep(0.1) return if k==win32con.VK_ESCAPE: globalkeyflag=win32con.VK_ESCAPE return try: if pwg_hotkey is not None: for n,hk in enumerate(pwg_hotkey.defhotkeys): if wparam==hk[1]: if pwg_hotkey.func[n] is not None: pwg_hotkey.func[n](wparam) #time.sleep(0.01) except: pass def OnLeftClick(self, hWnd, msg, wparam, lparam): x = win32api.LOWORD(lparam) y = win32api.HIWORD(lparam) if "CLICK" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel["CLICK"](self, x,y, lparam) #print 5822,lparam,wparam #print 5776,'Clic gauche', x,y def OnRightClick(self, hWnd, msg, wparam, lparam): x = win32api.LOWORD(lparam) y = win32api.HIWORD(lparam) #print 5784,'Clic droit', x,y """ def OnMouseUp(self, hWnd, msg, wparam, lparam): x = LOWORD(lparam) y = HIWORD(lparam) self.uWindow.event_mouseup(x,y,"L") def onChi(self, hWnd, msg, wparam, lparam): x = LOWORD(lparam) y = HIWORD(lparam) res = DefWindowProc(hWnd, msg, wparam, lparam) #ax = rc[0] - cr[0] #print "chi",x,y,res cm = {} cm[win32con.HTBOTTOM] = 'sizey' cm[win32con.HTLEFT] = 'sizex' cm[win32con.HTRIGHT] = 'sizex' cm[win32con.HTBOTTOMRIGHT] = 'sizeNW' cm[win32con.HTBOTTOMLEFT] = 'sizeNE' if res in cm.keys(): self.cursor = cm[res] else: #self.cursor = 'normal' pass return res def OnMouseMove(self, hWnd, msg, wparam, lparam): x = LOWORD(lparam) y = HIWORD(lparam) self.uWindow.event_mousemove(x,y) def OnClick(self, hWnd, msg, wparam, lparam): x = LOWORD(lparam) y = HIWORD(lparam) #print x,'v',y self.uWindow.event_mouseclick(x,y,"L") def OnClickR(self, hWnd, msg, wparam, lparam): x = LOWORD(lparam) y = HIWORD(lparam) #print x,'v',y self.uWindow.event_mouseclick(x,y,"R") """ def OnNotify(self, hwnd, msg, wparam, lparam): format = "PPiiiiiiiiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, llParam = struct.unpack(format, buf) #print 6547,idFrom if hwndFrom in self.allobj: idFrom=self.allobj[hwndFrom].id if msg==78: if code == -302: if "4901TITRECLICK" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel["4901TITRECLICK"](self, iItem,iSubItem) # dessin personnalisé (ListView et TreeView) if code==commctrl.NM_CUSTOMDRAW: #print 6559,hwndFrom,idFrom try: idFrom=self.allobj[hwndFrom].id #22.02.2012 : try/except except: pass if idFrom>4900 and idFrom<4910: # customdraw des ListView LPNMLVCUSTOMDRAW = ctypes.POINTER(win.NMLVCUSTOMDRAW) def CustomDraw(lpcd): if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_PREPAINT: return(True, commctrl.CDRF_NOTIFYITEMDRAW) if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_ITEMPREPAINT: # interception avant dessin ; traitement de chaque ligne lig=lpcd.contents.nmcd.dwItemSpec win32gui.SelectObject(lpcd.contents.nmcd.hdc,self.fonts["VLISTDEFAULT"]) return(True, commctrl.CDRF_NOTIFYSUBITEMDRAW) if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_ITEMPREPAINT|commctrl.CDDS_SUBITEM: # interception avant dessin ; on traite chaque colonne lig = lpcd.contents.nmcd.dwItemSpec col = lpcd.contents.iSubItem font=None # si on veut un arrière-plan : #lpcd.contents.clrTextBk=win32api.RGB(255,255,160) if str(idFrom)+"CDRAW" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel[str(idFrom)+"CDRAW"](self, lig, col) if isinstance(rparam,tuple): try: font=rparam[0] colorback=rparam[1] colortext=rparam[2] except: font=None colorback=None colortext=None if font is not None: win32gui.SelectObject(lpcd.contents.nmcd.hdc,self.fonts[font]) else: win32gui.SelectObject(lpcd.contents.nmcd.hdc,self.fonts["VLISTDEFAULT"]) if colorback is not None: lpcd.contents.clrTextBk=colorback else: lpcd.contents.clrTextBk=win32api.RGB(255,255,255) if colortext is not None: lpcd.contents.clrText=colortext else: lpcd.contents.clrText=win32api.RGB(0,0,0) return(False,False) return(False,False) #pour traiter la suite: ??? #return (True, commctrl.CDRF_SKIPDEFAULT) # don't need custom drawing return (True, commctrl.CDRF_DODEFAULT) lpcd = ctypes.cast(lparam, LPNMLVCUSTOMDRAW) retProc, retCode = CustomDraw(lpcd) return retCode if idFrom>4800 and idFrom<4810: # customdraw des TreeView LPNMTVCUSTOMDRAW = ctypes.POINTER(win.NMTVCUSTOMDRAW) def ShouldCustomDraw(row): return True def CustomDraw(lpcd): if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_PREPAINT: return(True, commctrl.CDRF_NOTIFYITEMDRAW) if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_ITEMPREPAINT: if ShouldCustomDraw(lpcd.contents.nmcd.dwItemSpec): h=lpcd.contents.nmcd.dwItemSpec nom=self.allobj[h].nom font=None if str(idFrom)+"CDRAW" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel[str(idFrom)+"CDRAW"](self, nom) if isinstance(rparam,tuple): try: font=rparam[0] colorback=rparam[1] colortext=rparam[2] except: font=None colorback=None colortext=None if font is not None: win32gui.SelectObject(lpcd.contents.nmcd.hdc,self.fonts[font]) if colorback is not None: lpcd.contents.clrTextBk=colorback if colortext is not None: lpcd.contents.clrText=colortext #level=lpcd.contents.iLevel if font is None: win32gui.SelectObject(lpcd.contents.nmcd.hdc,self.fonts["TREEDEFAULT"]) return(False,False) # don't need custom drawing return (True, commctrl.CDRF_DODEFAULT) lpcd = ctypes.cast(lparam, LPNMTVCUSTOMDRAW) retProc, retCode = CustomDraw(lpcd) return retCode if idFrom==12345: #scintilla sciformat = "iiiiPiiiPPiiii" #scibuf = win32ui.GetBytes( lparam, struct.calcsize(sciformat)) scibuf = win32gui.PyMakeBuffer(struct.calcsize(sciformat), lparam) position, ch, modifiers, modificationType, text_ptr, length, linesAdded, msg, wParam, lParam, line, foldLevelNow, foldLevelPrev, margin = struct.unpack(sciformat, scibuf) if code==SCI_CANCEL: #print 6019,"SCI: SCI_CANCEL" pass elif code==SCN_DOUBLECLICK: #print 6020,"SCI: Double-clic" pass elif code==SCN_MARGINCLICK: #print 6025,"SCN_MARGINCLICK" #print position, ch, modifiers, modificationType, text_ptr, length, linesAdded, msg, wParam, lParam, line, foldLevelNow, foldLevelPrev, margin rparam=self.grainsdesel[idFrom](self, "SCN_MARGINCLICK", modificationType) elif code==SCI_GETCHARAT: #print 6034,"SCI: SCI_GETCHARAT: modif-affichage" rparam=self.grainsdesel[idFrom](self, "SCI_GETCHARAT") elif code==SCN_UPDATEUI: #print 6030,"SCN_UPDATEUI: changement (affichage)" pass elif code==SCN_MODIFIED: #print 6034,"SCN_MODIFIED" rparam=self.grainsdesel[idFrom](self, "SCN_MODIFIED") pass """ print u"SCN_MODIFIED: modifié ; position:",iItem print iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, llParam print position, ch, modifiers, modificationType, text_ptr, \ length, linesAdded, msg, wParam, lParam, line, \ foldLevelNow, foldLevelPrev, margin """ elif code==SCN_PAINTED: #print 6052,"SCN_PAINTED" pass else: #print 6049,code pass """ def SCIUnpackNotifyMessage(msg): format = "iiiiPiiiPPiiii" bytes = win32ui.GetBytes( msg, struct.calcsize(format) ) position, ch, modifiers, modificationType, text_ptr, \ length, linesAdded, msg, wParam, lParam, line, \ foldLevelNow, foldLevelPrev, margin \ = struct.unpack(format, bytes) return (position,ch,modifiers,modificationType, text_ptr, length, linesAdded, msg, wParam, lParam, line, foldLevelNow, foldLevelPrev, margin) temp=SCIUnpackNotifyMessage(lparam) #print temp[6],code if code!=2013 and code!=2007 and code!=2008: if code==2001: print temp[3],temp[4] else: print temp print code,SCI_CHARLEFT print "num.chr:",temp[3] print "msg",temp[7] print "line:",temp[10] """ pass if code == commctrl.NM_DBLCLK: #if idFrom>4900 and idFrom<4910: # print "Double click sur ", iItem,iSubItem # pass if str(idFrom)+"LDOUBLECLICK" in self.grainsdesel: rparam=self.grainsdesel[str(idFrom)+"LDOUBLECLICK"](self, iItem,iSubItem) pass elif code == commctrl.NM_RCLICK: #if idFrom>4900 and idFrom<4910: # #print "Right click sur ", iItem,iSubItem # pass #elif if idFrom>4800 and idFrom<4810: # # hwndFrom == self.hTreeView == self.allobj[idFrom].hwnd self.callmenu() elif code == commctrl.NM_RDBLCLK: if idFrom>4900 and idFrom<4910: #print "Right double-click sur", iItem,iSubItem pass pass elif code == commctrl.NM_CLICK: #print "3444 click sur", iItem,iSubItem if idFrom>4900 and idFrom<4910: #print "3444 click sur", iItem,iSubItem try: self.ligcourante=iItem self.colcourante=iSubItem #print iSubItem except: #print pass elif code==commctrl.TVN_SELCHANGING: if idFrom>4800 and idFrom<4810: # hwndFrom == self.hTreeView data=win.UnpackTVNOTIFY(lparam) de=data[4][0] vers=data[5][0] if de==0: denom=None else: denom=self.allobj[de].nom noeud=self.allobj[vers] self.arbrenomcourant=noeud.nom #print " vers", noeud.nom,'('+str(vers)+")", noeud.id," data",noeud.data.encode('cp1252','ignore')," mask+images",noeud.coche,noeud.image,noeud.image2 if str(idFrom)+"CHANGEITEM" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel[str(idFrom)+"CHANGEITEM"](self, denom,noeud.nom) elif code == commctrl.LVN_ITEMCHANGING: # pas de sous-item en se déplaçant par ligne entière if idFrom>4900 and idFrom<4910: if self.ligcourante!=iItem: try: self.ligcourante=iItem self.colcourante=iSubItem except: pass if str(idFrom)+"CHANGEITEM" in self.grainsdesel: if self.grainsdeselflag==0: rparam=self.grainsdesel[str(idFrom)+"CHANGEITEM"](self, iItem,iSubItem) else: #autres cas non (encore) traités pass return 0 def OnClose(self, hwnd, msg, wparam, lparam): if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: return 0 if self.navig is not None: self.navig.close() self.navig=None if self.ffille: try: """ if self.origparent: win32gui.CloseWindow(self.ffille) temp=ctypes.windll.user32.SetParent(self.ffille, self.origparent) self.origparent=False time.sleep(0.01) win32gui.MoveWindow(self.ffille, 10,10, 600,400, 0) time.sleep(0.01) """ win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) ##win32gui.DestroyWindow(self.ffille) time.sleep(0.250) except: pass self.ffille=False self.mmclose() win32gui.DestroyWindow(hwnd) win32gui.PumpWaitingMessages() time.sleep(0.1) self.duree=0 def OnClose2(self, hwnd, msg, wparam, lparam): if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: return 0 if self.navig is not None: self.navig.close() self.navig=None if self.ffille: try: """ if self.origparent: win32gui.CloseWindow(self.ffille) temp=ctypes.windll.user32.SetParent(self.ffille, self.origparent) self.origparent=False time.sleep(0.01) win32gui.MoveWindow(self.ffille, 10,10, 600,400, 0) time.sleep(0.01) """ win32gui.SendMessage(self.ffille, win32con.WM_CLOSE, 0,0) time.sleep(0.1) win32gui.CloseWindow(self.ffille) ##win32gui.DestroyWindow(self.ffille) time.sleep(0.250) except: pass self.ffille=False self.mmclose() win32gui.DestroyWindow(hwnd) ###win32gui.PumpWaitingMessages() time.sleep(0.1) self.duree=0 def wmcopydata(self, hwnd, msg, wparam, lparam): format = "iiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) a,b,c = struct.unpack(format, buf) # a,b = longueur ; c=pointeur data = win32gui.PyGetString(c) if 'WM_COPYDATA' in self.grainsdesel: if self.grainsdeselflag==0: self.grainsdesel['WM_COPYDATA'](self,"window","WM_COPYDATA", data) def wmhotkey(self, hwnd, msg, wparam, lparam): #print 4929,wparam,msg.wParam """ format = "iiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) a,b,c = struct.unpack(format, buf) # a,b = longueur ; c=pointeur data = win32gui.PyGetString(c) if 'WM_HOTKEY' in self.grainsdesel: self.grainsdesel['WM_HOTKEY'](self,"window","WM_HOTKEY", data) # vret = pwg_hotkey.func[msg.wParam](pwg_hotkey.par[msg.wParam]) """ pass def OnDestroy(self, hwnd, msg, wparam, lparam): if self.navig is not None: self.navig.close() self.navig=None self.duree=0 win32gui.PostQuitMessage(0) # ou (1) ? def calcresult(self): self.result={} for id in self.edits: el=self.edits[id] try: ctrl = el.hwnd tct=self.getedittext(ctrl) self.result[id]=self.getedittext(ctrl) except: self.result[id]=[None] def contenuchamp(self, el): """ dernier contenu de champ, calculé avec calcresult """ vret = self.result[el.id] if len(vret)==1: return vret[0] else: return vret def OnCommand(self, hwnd, msg, wparam, lparam, pseudoid=None): global global_TEST, dernierecommand,derniereparam if pseudoid is None: #id=win32api.LOWORD(wparam) pass else: #id=pseudoid lparam=pseudoid try: #""" pour table format = "PPiiiiiiiiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam = struct.unpack(format, buf) except: hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam = [None]*11 #print 5390,win32api.LOWORD(wparam),win32api.HIWORD(wparam) ''' #if global_TEST: if True: print 5390,win32api.LOWORD(wparam),win32api.HIWORD(wparam) print hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam global_TEST=False ''' """ win32api.HIWORD(wparam) == 256 # 256 changement de champ ? à vérifier win32api.HIWORD(wparam) == 512 # 512 quitte le champ ? à vérifier """ if lparam==0: id=win32api.LOWORD(wparam) el=self.allobj[id] try: el=self.allobj[lparam] id=lparam except: id=wparam try: tmp=el except: el=None self.derCommand=lparam self.derCommandid=id changementedit=None if isinstance(el,win.elementedit): if win32api.HIWORD(wparam)==256: if self.editcourant != el: chprior=self.editcourant self.editcourant=el changementedit=(chprior,el) #print 5242,lparam #print "On a quitté",chprior #print "pour arriver sur",self.editcourant #print if chprior in self.grainsdesel: if self.grainsdeselflag==0: if self.grainsdesel[chprior] in (self.valide,self.abandon): self.grainsdesel[chprior](el, 'QUITTED',changementedit) else: self.grainsdesel[chprior](self, el, 'QUITTED',changementedit) try: #print 7017,"el:", #print el,lparam,id,' ',type(el),type(id) if el in self.grainsdesel: if self.grainsdeselflag==0: if self.grainsdesel[el] in (self.valide,self.abandon): if el!=7777: dernierecommand=self.grainsdesel[el] derniereparam=(el, 'COMMAND',changementedit) self.grainsdesel[el](el, 'COMMAND',changementedit) else: if el!=7777: dernierecommand=self.grainsdesel[el] derniereparam=(self, el, 'COMMAND',changementedit) self.grainsdesel[el](self, el, 'COMMAND',changementedit) elif lparam==0: if id in self.grainsdesel: if self.grainsdeselflag==0: if id!=7777: dernierecommand=self.grainsdesel[id] derniereparam=(self, id, 'COMMAND',changementedit) self.grainsdesel[id](self, id, 'COMMAND',changementedit) except: if pdebug: raise pass def repetedernierecommand(self,*par): dernierecommand(*derniereparam) time.sleep(0.250) def OnCommand2(self, hwnd, msg, wparam, lparam, pseudoid=None): global global_TEST if pseudoid is None: #id=win32api.LOWORD(wparam) pass else: #id=pseudoid lparam=pseudoid try: #""" pour table format = "PPiiiiiiiiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam = struct.unpack(format, buf) except: hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam = [None]*11 #print 5390,win32api.LOWORD(wparam),win32api.HIWORD(wparam) ''' #if global_TEST: if True: print 5390,win32api.LOWORD(wparam),win32api.HIWORD(wparam) print hwndFrom, idFrom, code, iItem, iSubItem, uNewState, uOldState, uChanged, actionx, actiony, lParam global_TEST=False ''' """ win32api.HIWORD(wparam) == 256 # 256 changement de champ ? à vérifier win32api.HIWORD(wparam) == 512 # 512 quitte le champ ? à vérifier """ el=msg.hwnd """ if lparam==0: id=win32api.LOWORD(wparam) el=self.allobj[id] """ try: el=self.allobj[lparam] id=lparam except: id=wparam try: tmp=el except: el=None self.derCommand=lparam self.derCommandid=id changementedit=None if isinstance(el,win.elementedit): if win32api.HIWORD(wparam)==256: if self.editcourant != el: chprior=self.editcourant self.editcourant=el changementedit=(chprior,el) #print 5242,lparam #print "On a quitté",chprior #print "pour arriver sur",self.editcourant #print if chprior in self.grainsdesel: if self.grainsdeselflag==0: if self.grainsdesel[chprior] in (self.valide,self.abandon): self.grainsdesel[chprior](el, 'QUITTED',changementedit) else: self.grainsdesel[chprior](self, el, 'QUITTED',changementedit) try: #print 5253,"el:", #print el,lparam,id if el in self.grainsdesel: if self.grainsdeselflag==0: if self.grainsdesel[el] in (self.valide,self.abandon): self.grainsdesel[el](el, 'COMMAND',changementedit) else: self.grainsdesel[el](self, el, 'COMMAND',changementedit) elif lparam==0: if id in self.grainsdesel: if self.grainsdeselflag==0: self.grainsdesel[id](self, id, 'COMMAND',changementedit) except: if pdebug: raise pass def mmopen(self,ID='PYWIG_DORMIR'): import mmap self.mmap=mmap.mmap(0,32767,ID) def mmwrite(self,data): import mmap self.mmap.seek(0) self.mmap.write(data) self.mmap.flush() def mmread(self): import mmap self.mmap.seek(0) data=self.mmap.read(32767) #print 83,data[:30]+"**" return data def mmclose(self): import mmap if self.mmap is not None: self.mmap.close() self.mmap=None def dors(self, *suite): # fenêtre en train de dormir (en attente de réveil) while True: mdata=self.mmread() if mdata[:6]=="REVEIL": self.visible(True) break time.sleep(0.1) self.mmclose() if 'REVEIL' in self.grainsdesel: self.grainsdesel['REVEIL'](self,"window",'REVEIL',mdata[7:]) def dormir(self, ID='PYWIG_DORMIR', pvisible=True, *suite): # endors la fenêtre courante self.mmopen(ID) self.mmwrite('DORMIR') if pvisible==False: self.visible(False) self.dors() def selfdormir(self, win, ID='PYWIG_DORMIR', pvisible=True, *suite): # endors la fenêtre courante (autoappel) self.dormir(ID,pvisible,*suite) def forcecommand(self,id=None): pass #print self.OnCommand(0,0,0,0,pseudoid=id) def run(self, dureemax=3600*24, initf=None, initpar=[]): global wtop,wtopctrl,kprec,ktime,kprecnb,globalkeyflag msg = MSG() premsg = MSG() if initf is not None: win32gui.PumpWaitingMessages() initf(self,*initpar) if self.duree>0: self.duree=dureemax deb=time.time() #if wtop is None: # wtop=self while True: aw=win32gui.GetActiveWindow() if aw==0: tmp=win32gui.GetForegroundWindow() if tmp==self.hwnd: self.active() aw=win32gui.GetActiveWindow() if aw == self.hwnd: if self.scintilla is not None: if ctypes.windll.user32.GetFocus() != self.scintilla: ctypes.windll.user32.SetFocus(self.scintilla) #time.sleep(0.1) else: if wtop is not None: if wtop!=0: if aw != wtop.hwnd: self.active() #time.sleep(0.1) if wtopctrl is not None: self.ctrlfocus(wtopctrl) aw=win32gui.GetActiveWindow() if (aw==0) or (aw is None): if (win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000): if win32gui.GetForegroundWindow() == self.ffille: self.active() #print 3714,"{Echap}",aw, self.hwnd, self.ffille,win32gui.GetForegroundWindow() """ if msg.message==win32con.WM_CTLCOLORSTATIC: print 5785 result = win32gui.SetTextColor(self.hwnd, win32api.RGB(127,222,0)) """ k=None if aw == self.hwnd: k=None if win32api.GetAsyncKeyState(win32con.VK_RETURN) & 0x8000: k=win32con.VK_RETURN if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): #tmpmsg=premsg.message ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) if msg.message==win32con.WM_KEYFIRST or msg.message==win32con.WM_KEYUP or msg.message==win32con.WM_KEYDOWN or msg.message==win32con.WM_SYSKEYDOWN: k=msg.wparam if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: k=win32con.VK_ESCAPE if k is None: if globalkeyflag: k=globalkeyflag globalkeyflag=False """ if globalkeyflag==win32con.VK_ESCAPE: k=win32con.VK_ESCAPE globalkeyflag=False if globalkeyflag==win32con.VK_RETURN: k=win32con.VK_RETURN globalkeyflag=False """ if k==win32con.VK_RETURN: sci_flag=False try: temp=SCI_START sci_flag=True except: sci_flag=False #print 7314,k,win32con.VK_RETURN,sci_flag #print 7315,self.grainkey[k] #print 7316,self.grainsdeselflag if sci_flag and not((k==win32con.VK_RETURN) and (k in self.grainkey)) : ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) continue elif self.etat is not None: #cas de validation d'un menu popup time.sleep(0.01) ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) time.sleep(0.05) if isinstance(self.etat,float): if (time.time()-self.etat)>0.25: self.etat=None else: flag=False continue else: if True: k=win32con.VK_RETURN flag_k=False keycompl="" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" if k==win32con.VK_RETURN: self.bufkey=k flag_k=True if keycompl=="" or keycompl=="Shift+" or keycompl=="Ctrl+": el=self.getfocus() if isinstance(el,win.elementedit): if self.grainkey[k] == win.champsuivant: if self.grainsdeselflag==0: if el.multiligne: flag_k=True if (keycompl == "Ctrl+"): ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) #time.sleep(0.01) win32api.keybd_event(win32con.VK_RETURN, 0, 0, 0) time.sleep(0.02) win32api.keybd_event(win32con.VK_RETURN, 0, win32con.KEYEVENTF_KEYUP, 0) #time.sleep(0.01) if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) #time.sleep(0.01) if self.grainsdeselflag==0: try: self.grainkey[k](self,"window",'KEY_'+keycompl) except: pass """ if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): tmpmsg=premsg.message ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) """ ktime=time.time() #win32gui.PumpWaitingMessages() while (time.time()-ktime)<0.15: if win32api.GetAsyncKeyState(k) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break continue if ('KEY' in self.grainsdesel): flag=True if isinstance(self.etat,float): if (time.time()-self.etat)>0.25: self.etat=None else: flag=False if flag: flag=False if True: k=None self.bufkey=None for k in self.grainkey: if win32api.GetAsyncKeyState(k) & 0x8000: self.bufkey=k flag=True break k=self.bufkey if not flag: kprec=-999 if flag: keycompl="" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" flag_k=True if flag_k: #win32gui.PumpWaitingMessages() if self.grainsdeselflag==0: #print 7324, win32gui.GetActiveWindow(), self.hwnd,win32gui.GetForegroundWindow(),time.time() try: aaa=self.grainkey[k](self,"window",'KEY_'+keycompl) if aaa or aaa is None: if not k in (win32con.VK_UP, win32con.VK_DOWN, win32con.VK_PRIOR, win32con.VK_NEXT, win32con.VK_END, win32con.VK_RETURN, win32con.VK_ESCAPE): ktime=time.time() while (time.time()-ktime)<0.10: if win32api.GetAsyncKeyState(k) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break except: pass if kprec == k: if (time.time()-ktime)>0.3: if (time.time()-ktime)<1.0: time.sleep(0.05) win32gui.PumpWaitingMessages() else: pass #rafraichissement tous les 3 évènements kprecnb+=1 if int(kprecnb/3.0)*3 == kprecnb: win32gui.PumpWaitingMessages() else: win32gui.PumpWaitingMessages() while (time.time()-ktime)<0.3: if win32api.GetAsyncKeyState(k) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break else: ktime=time.time() kprec = k kprecnb=0 if k not in (win32con.VK_UP, win32con.VK_DOWN): win32gui.PumpWaitingMessages() for i in range(10): if win32api.GetAsyncKeyState(k) & 0x8000: time.sleep(0.01) else: break if k==win32con.VK_UP or k==win32con.VK_DOWN: if not win32api.GetAsyncKeyState(k) & 0x8000: win32gui.PumpWaitingMessages() win32gui.SendMessage( self.getfocus().hwnd, win32con.EM_SETSEL, 0, 50) if self.duree==signal_invisible: self.duree=3600*12 if self.isvisible(): self.visible(False) while True: time.sleep(0.05) win32gui.PumpWaitingMessages() #if win32api.GetKeyState(win32con.VK_CONTROL) & 0x8000: if win32api.GetAsyncKeyState(222) & 0x8000: break #win32gui.PumpWaitingMessages() self.visible(True) self.duree=3600*12 self.settop() #time.sleep(0.01) nb_return=0 aw=win32gui.GetActiveWindow() if "REDEVIENT_VISIBLE" in self.grainsdesel: self.grainsdesel["REDEVIENT_VISIBLE"](self,"window","REDEVIENT_VISIBLE",0) self.heuredebutinvisible=None continue #time.sleep(0.1) #if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: # if self.hwnd == win32gui.GetActiveWindow(): # k=win32con.VK_ESCAPE flag=False #if k==win32con.VK_ESCAPE: if (k==win32con.VK_ESCAPE or (win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000)) and (self.hwnd == win32gui.GetForegroundWindow()): flag=True if isinstance(self.etat,float): if (time.time()-self.etat)>0.250: self.etat=None else: flag=False else: if k is None: if win32api.GetKeyState(win32con.VK_ESCAPE) & 0x8000: ktime=time.time() while (time.time()-ktime)<0.250: if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break time.sleep(0.001) flag=True if isinstance(self.etat,float): if (time.time()-self.etat)>0.250: self.etat=None else: flag=False if flag: #********************** si {Echap} => Menu keycompl="" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" if keycompl=="": win32api.keybd_event(win32con.VK_ESCAPE, 0, win32con.KEYEVENTF_KEYUP, 0) ### ??? win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) time.sleep(0.01) if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): tmpmsg=premsg.message ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) #win32gui.PumpWaitingMessages() #print self.scintilla #print 7486,time.time(),self.titre self.callmenu() if (win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000) or k==win32con.VK_ESCAPE: #print 7490 ktime=time.time() while (time.time()-ktime)<0.10: if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break if k is not None: if k==win32con.VK_RETURN: if (win32api.GetAsyncKeyState(win32con.VK_RETURN) & 0x8000) and (self.hwnd == win32gui.GetForegroundWindow()): if ctypes.windll.user32.PeekMessageA(ctypes.pointer(premsg), self.hwnd, 0, 0, 0): tmpmsg=premsg.message ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.01) else: win32gui.PumpWaitingMessages() time.sleep(0.01) if self.runinjected != []: for lcde in self.runinjected: lcde[0](self,*lcde[1:]) self.runinjected = [] if self.timerfonction is not None: if time.time()-self.timerdebut > self.timerdelai: vret=self.timerfonction(self,"timer",self.timerdebut) if vret: self.timerdebut=time.time() else: self.timerfonction=None if time.time()-deb>self.duree: if self.duree == signal_invisible: if win32api.GetAsyncKeyState(222) & 0x8000: nb_return=0 while win32api.GetAsyncKeyState(222) & 0x8000: win32gui.PumpWaitingMessages() nb_return+=1 if nb_return>6: break time.sleep(0.01) else: break if self.modeinvisible=="WAIT": if not self.isvisible(): self.heuredebutinvisible=time.time() while True: time.sleep(0.024) if self.isvisible() or (time.time()-self.heuredebutinvisible>self.dureeinvisible): if "REDEVIENT_VISIBLE" in self.grainsdesel: self.grainsdesel["REDEVIENT_VISIBLE"](self,"window","REDEVIENT_VISIBLE",time.time()-self.heuredebutinvisible>self.dureeinvisible) self.heuredebutinvisible=None break else: if self.heuredebutinvisible is not None: if "REDEVIENT_VISIBLE" in self.grainsdesel: self.grainsdesel["REDEVIENT_VISIBLE"](self,"window","REDEVIENT_VISIBLE",time.time()-self.heuredebutinvisible>self.dureeinvisible) self.heuredebutinvisible=None #win32gui.PumpWaitingMessages() if self.duree==-333: self.visible(False) time.sleep(0.01) else: if self.pyw: del self.pyw self.ferme() def run2(self, dureemax=3600*24, initf=None, initpar=[]): global wtop,wtopctrl if initf is not None: #win32gui.PumpWaitingMessages() initf(self,*initpar) if self.duree>0: self.duree=dureemax deb=time.time() #if wtop is None: # wtop=self compteur=0 msg = MSG() flag_k=False while True: if time.time()-deb>self.duree: break time.sleep(0.01) #z=ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), 0, 0, 0, 0) #if z != 0: # print z if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): #if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), 0, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) #while ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0): """ if msg.message==0: print 5585,"ZERO" win32gui.SendMessage(self.hwnd, win32con.WM_CLOSE, 0,0) time.sleep(0.1) self.duree=0 break """ if msg.message != win32con.WM_MOUSEFIRST and msg.message != win32con.WM_MOUSEMOVE and msg.message != win32con.WM_NCMOUSEMOVE: for i in dir(win32con): if i.startswith("WM_"): if msg.message == eval("win32con."+i): print msg.message,i """ aw=win32gui.GetActiveWindow() if aw==0: tmp=win32gui.GetForegroundWindow() if tmp==self.hwnd: self.active() aw=win32gui.GetActiveWindow() if aw != self.hwnd: if wtop is not None: if wtop!=0: if aw != wtop.hwnd: self.active() #time.sleep(0.1) if wtopctrl is not None: self.ctrlfocus(wtopctrl) aw=win32gui.GetActiveWindow() """ """ if msg.message==win32con.WM_PAINT: #print 5633,"PAINT",self.hwnd, msg.hwnd if self.hwnd==msg.hwnd: self.OnPaint(self.hwnd, msg, msg.wparam, msg.lparam) else: ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) continue """ """ elif msg.message==win32con.WM_COMMAND: print 5635,"COMMAND",msg.wparam, msg.lparam self.OnCommand2(self.hwnd, msg, msg.wparam, msg.lparam) elif msg.message==win32con.WM_CLOSE: print 5638,"CLOSE" ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) self.OnClose2(self.hwnd, msg, msg.wparam, msg.lparam) break elif msg.message==win32con.WM_QUIT: print 5632,"QUIT" break elif msg.message==win32con.WM_DESTROY: print 5651,"DESTROY" self.OnDestroy(self.hwnd, msg, msg.wparam, msg.lparam) elif msg.message==win32con.WM_NOTIFY: print 5651,"NOTIFY" self.OnNotify(self.hwnd, msg, msg.wparam, msg.lparam) elif msg.message==win32con.WM_COPYDATA: print 5651,"COPYDATA" self.wmcopydata(self.hwnd, msg, msg.wparam, msg.lparam) """ #print 5577,msg.message,msg.pt,msg.hwnd if msg.message==win32con.WM_LBUTTONDOWN or msg.message==win32con.WM_NCLBUTTONDOWN: ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) #print 5670,msg.message, msg.hwnd, msg.wparam, win32api.LOWORD(msg.wparam),' lparam:', msg.lparam """ if msg.hwnd==self.hwnd: if win32api.LOWORD(msg.wparam)==20: #ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) #ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) #print 5673,self.hwnd # marche pas ? win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) print 5686 win32gui.PostQuitMessage(0) flag_k=True self.duree=0 break """ """ # msg.hwnd est le hwnd de la cible de l'évènement print 5679,"CLIC",msg.hwnd, msg.hwnd in self.allobj, self.hwnd, win32gui.GetActiveWindow() try: if msg.hwnd in self.allobj: el=self.allobj[msg.hwnd] id=el.id print 5685,id," ",el.hwnd #,self.grainsdesel[el] if win32api.LOWORD(msg.wparam) in self.allobj: print 5686,self.allobj[win32api.LOWORD(msg.wparam)] if el in self.grainsdesel: print 5691 self.grainsdesel[el](el, 'CLIC',0) elif msg.lparam==0: print 5697 if id in self.grainsdesel: self.grainsdesel[id](id, 'CLIC',0) print 5700 ctypes.windll.user32.PostQuitMessage(0) #for i in range(29): # time.sleep(0.01) # win32gui.PumpWaitingMessages() except: if pdebug: raise pass """ #print 5599,msg.message, msg.hwnd, msg.wparam, win32api.LOWORD(msg.wparam),' lparam:', msg.lparam ''' if msg.lparam==0: id=win32api.LOWORD(msg.wparam) el=self.allobj[id] try: el=self.allobj[msg.lparam] id=msg.lparam except: id=msg.wparam try: tmp=el except: el=None ''' if msg.message==win32con.WM_KEYDOWN or msg.message==win32con.WM_SYSKEYDOWN: k=msg.wparam flag_k=False keycompl="" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" if k==115 and keycompl=="Alt+": #print 5740,"Alt-F4" self.duree=0 self.ferme() break if k==win32con.VK_ESCAPE: if win32gui.GetForegroundWindow() == self.ffille: self.active() self.callmenu() flag_k=True #win32gui.SendMessage(self.hwnd,win32con.WM_SYSCOMMAND,0,0); if ('KEY' in self.grainsdesel): flag=True if isinstance(self.etat,float): if (time.time()-self.etat)>0.25: self.etat=None else: flag=False if flag: flag=False for tmpk in self.grainkey: if tmpk==k: self.bufkey=k flag=True break if flag: k=self.bufkey flag_k=True if k==win32con.VK_RETURN: if keycompl=="" or keycompl=="Shift+" or keycompl=="Ctrl+": nb_return=0 while win32api.GetAsyncKeyState(k) & 0x8000: time.sleep(0.02) nb_return+=1 if nb_return>9: break el=self.getfocus() if isinstance(el,win.elementedit): if self.grainkey[k] == win.champsuivant: if el.multiligne: flag_k=True if (keycompl != "Ctrl+"): pass #+++ à revoir if flag_k==False: pass else: """ self.allobj[msg.hwnd] est la cible de l'évènement """ if self.grainsdeselflag==0: #print 5748,self,self.allobj[msg.hwnd],k,'KEY_'+keycompl,self.grainkey[k] self.grainkey[k](self,self.allobj[msg.hwnd],'KEY_'+keycompl) #print 5750,flag_k if self.modeinvisible=="WAIT": if not self.isvisible(): self.heuredebutinvisible=time.time() while True: time.sleep(0.024) if self.isvisible() or (time.time()-self.heuredebutinvisible>self.dureeinvisible): if "REDEVIENT_VISIBLE" in self.grainsdesel: self.grainsdesel["REDEVIENT_VISIBLE"](self,"window","REDEVIENT_VISIBLE",time.time()-self.heuredebutinvisible>self.dureeinvisible) self.heuredebutinvisible=None break else: if self.heuredebutinvisible is not None: if "REDEVIENT_VISIBLE" in self.grainsdesel: self.grainsdesel["REDEVIENT_VISIBLE"](self,"window","REDEVIENT_VISIBLE",time.time()-self.heuredebutinvisible>self.dureeinvisible) self.heuredebutinvisible=None if not flag_k: print 7772 ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) if self.duree==-333: #print 5817,self.duree self.visible(False) time.sleep(0.01) compteur+=1 #print 5877,"ferme" if not flag_k: ctypes.windll.user32.TranslateMessage(ctypes.pointer(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.pointer(msg)) if self.pyw: del self.pyw pass self.ferme() ctypes.windll.user32.PostQuitMessage(0) time.sleep(0.01) def valide(self, id, event, *suite): self.calcresult() self.fin="VALIDE" self.ferme() def abandon(self, id, event, *suite): self.calcresult() self.fin="ABANDON" self.ferme() class mg_ligne(object): """ mg = Multi-Groupes """ def __init__(self, nbligvisu=0, nblig=0, x=0,y=0, l=700,h=100, champs=[], textes=[],flagdessin=True): self.nbligvisu=nbligvisu self.nblig=nblig ''' if nblig=self.nbligvisu: ligvd=ligvd-self.nbligvisu if ligvd<0: ligvd=0 lt=self.dessin[ligvd].dessin.split('\n') if int(self.lcourant/2.0)*2 == self.lcourant: tbrush="255 240 255" else: tbrush="240 255 255" lt[2]="brush "+tbrush self.dessin[ligvd].dessin = '\n'.join(lt) except: pass self.w.redessine() def chglcourant(self, newligne=None, tmplvisu=None): if self.lcourant != newligne: """ print "ligdepart",self.lcourant print "ligarrive",newligne print "lvisu",self.lvisu """ if tmplvisu is None: tmplvisu=self.lvisu if self.surlignage: try: ligvd=self.lcourant-tmplvisu #ligne visu départ if ligvd>=self.nbligvisu: ligvd-=-self.nbligvisu if ligvd>=self.nbligvisu: ligvd=self.nbligvisu-1 if ligvd<0: ligvd+=self.nbligvisu if ligvd<0: ligvd=0 lt=self.dessin[ligvd].dessin.split('\n') if int(self.lcourant/2.0)*2 == self.lcourant: tbrush="255 150 255" else: tbrush="150 255 255" lt[2]="brush "+tbrush self.dessin[ligvd].dessin = '\n'.join(lt) except: pass try: ligva=newligne-tmplvisu #ligne visu arrivée if ligva>self.nbligvisu: ligva=ligva-self.nbligvisu if ligva>=self.nbligvisu: ligva=self.nbligvisu-1 if ligva<0: ligva=0 lt=self.dessin[ligva].dessin.split('\n') tbrush="255 255 64" lt[2]="brush "+tbrush self.dessin[ligva].dessin = '\n'.join(lt) except: pass self.w.redessine() #print 5896,self.lcourant,newligne if self.lcourant>-1 and self.lcourant-self.lvisu>-1: self.majval(self.lcourant) #self.majval(newligne) ''' if newligne==3: ligva=newligne-tmplvisu #ligne visu arrivée if ligva<0: ligva=0 if ligva>self.nbligvisu: ligva=self.nbligvisu lt=self.dessin[ligva].dessin.split('\n') tbrush="255 255 64" lt[2]="brush "+tbrush self.dessin[ligva].dessin = '\n'.join(lt) if self.lcourant==3: ligvd=self.lcourant-tmplvisu #ligne visu départ if ligvd<0: ligvd=0 if ligvd>self.nbligvisu: ligvd=self.nbligvisu lt=self.dessin[ligvd].dessin.split('\n') if int(self.lcourant/2.0)*2 == self.lcourant: tbrush="255 240 255" else: tbrush="240 255 255" lt[2]="brush "+tbrush self.dessin[ligvd].dessin = '\n'.join(lt) ''' if self.flagdessin: self.w.redessine() # autre traitement éventuel ligne départ if newligne is not None: self.lcourant=newligne self.w.ligcourante=newligne def setlvisu(self, lvisu=None, newligne=None): """ lvisu est le num de ligne qui correspond à 1ere ligne visualisée newligne est la nouvelle ligne absolue "forcée" """ if lvisu is None: lvisu=self.lvisu if self.lvisu != lvisu: self.lvisu = lvisu self.valvisu(self.lvisu) def graindeselkey(self,w,**kw): """ réaffecter un grain de sel key (clavier) """ w.graindeselkey(**kw) def graindesel(self,w,numchamp,fonction): for lig in range(self.nbligvisu): w.graindesel(self.h[lig][numchamp],fonction) def majtext(self,w, lig=None,numtxt=0, texte="Texte"): if lig is None: lig=self.lcourant #w.majtext(self.htxt[lig][numtxt],texte) w.majtextseul(self.htxt[lig][numtxt],texte) def visu(self,w): self.w=w w.multigroup=self self.w.ligcourante=self.lcourant w.add_font("TXTLCHAMP","Arial narrow", 20) w.add_font("TXTLABEL","Arial narrow", 22) hautlabel=18 for lig in range(self.nbligvisu): ajoutv=lig*self.hautlig if int(lig/2.0)*2 == lig: tbrush="255 240 255" else: tbrush="240 255 255" self.dessin.append(w.add_dessin("""color 230 230 230 pen 0 1 brush """+tbrush+""" rectangle """+str(self.x)+" "+str(ajoutv+self.y)+" "+str(self.larglig)+" "+str(self.hautlig+ajoutv+self.y)+""" """)) for i,ch in enumerate(self.chl): #self.h[lig][i]= w.add_edit(ch.x+self.x,ch.y+ajoutv+self.y, ch.l,ch.h, ch.multiligne, False, ch.mlscroll, ch.font, ch.format, ch.align, g_lig=lig, g_col=i, textcolor=ch.textcolor) self.h[lig][i]= w.add_edit(ch.x+self.x,ch.y+ajoutv+self.y, ch.l,ch.h, ch.multiligne, False, ch.mlscroll, ch.font, ch.format, ch.align, g_lig=lig, g_col=i) self.h[lig][i].win=w if ch.border: w.add_editborder(self.h[lig][i]) self.h[lig][i].ligne=lig self.h[lig][i].numdanslig=i self.h[lig][i].ogroupe=self self.h[lig][i].format=ch.format self.h[lig][i].align=ch.align self.chlig[self.h[lig][i]]=lig if ch.label is not None: w.add_text(texte=ch.label,x=ch.x+self.x+2,y=ch.y+self.y+ajoutv-hautlabel-2,l=ch.l-2,h=hautlabel, multiligne=False, font="TXTLABEL", textcolor=(64,64,64)) for i,ch in enumerate(self.textes): self.htxt[lig][i]= w.add_text(texte=ch.texte,x=ch.x+self.x, y=ch.y+ajoutv+self.y, l=ch.l, h=ch.h, multiligne=ch.multiligne, font=ch.font, textcolor=ch.textcolor,align=ch.align, g_lig=lig, g_col=i) self.htxt[lig][i].ligne=lig self.htxt[lig][i].numdanslig=i self.htxt[lig][i].ogroupe=self self.htxt[lig][i].align=ch.align w.graindeselkey(VK_DELETE=self.gmdeletelig, VK_INSERT=self.gminsertlig, VK_DOWN=self.suitdown, VK_UP=self.suitup, VK_NEXT=self.suitpagedown, VK_PRIOR=self.suitpageup, VK_END=self.suitend, VK_HOME=self.suithome) self.graindesel(w,self.nbchamps-1,self.suivivalid) def lclire(self,lig=None,col=1): """ récupère les valeurs de la ligne absolue lig pour la colonne col """ if lig is None: lig=self.lcourant else: self.lcourant=lig if lig>=self.nblig: self.gmajoutlig() # lig=self.nblig-1 return self.h[lig-self.lvisu][col].fast1lirecontenu(format=self.chl[col].format) #return self.htxt[lig-self.lvisu][num].texte def lcecrire(self,lig=None,col=1, valeur=None): """ affecte une valeurs de la ligne absolue lig pour la colonne col (doit déjà exister) """ if lig is None: lig=self.lcourant else: self.lcourant=lig if lig>=self.nblig: self.gmajoutlig() self.majval() #lig=self.nblig-1 self.val[lig][col]=valeur self.h[lig-self.lvisu][col].fast1contenu(valeur,format=self.chl[col].format) def majval(self,lig=None): """ récupère les valeurs de la ligne absolue lig """ if lig is None: lig=self.lcourant else: self.lcourant=lig if lig<0: return if self.nblig==0: tmpl=[] for c in range(self.nbchamps): tmpl.append(u"") self.val.append(tmpl) tmpl=[] for t in range(self.nbtextes): tmpl.append(u"") self.txtval.append(tmpl) self.nblig+=1 if lig>=self.nblig: lig=self.nblig-1 self.lcourant=lig #print 8100,lig,len(self.val),self.nblig,self.lcourant,self.nbchamps #if lig>0 and liglig: #print 8205, self.lvisu, lig #self.lvisu=lig pass #win32gui.SendMessage( self.h[lig][numchamp].hwnd, win32con.EM_SETSEL, 0, 0) #win32gui.PumpWaitingMessages() self.chglcourant(lig+self.lvisu) #, tmplvisu=self.lvisu) #self.valvisu() """ length = win32gui.GetWindowTextLength(self.handle) win32gui.SendMessage(self.handle, win32con.EM_SETSEL, length, length) win32gui.SendMessage(self.handle, win32con.EM_REPLACESEL, False, data) """ def focusdebutdeb(self,numchamp=0): # va au 1er champ de la 1ère ligne absolue #self.h[0][0].win.ctrlfocus(self.h[1][0]) self.h[0][0].win.ctrlfocus(self.h[1][0]) self.chglcourant(1) self.h[0][0].win.ctrlfocus(self.h[0][0]) self.chglcourant(0) self.valvisu(0) def focusdebutder(self,numchamp=0): # va au 1er champ de la dernière ligne absolue self.h[0][0].win.ctrlfocus(self.h[self.nbligvisu-1][0]) self.chglcourant(self.nblig-1) def focusfinder(self,numchamp=0): # va au dernier champ de la dernière ligne absolue #self.chglcourant(self.nblig) self.h[0][0].win.ctrlfocus(self.h[self.nbligvisu-1][self.nbchamps-1]) def focusdebutlig(self,ligne=0): """ ligne = n° ligne ds visu """ self.h[0][0].win.ctrlfocus(self.h[ligne][0]) def gmajoutlig(self): tmpl=[] for c in range(self.nbchamps): tmpl.append(u"") tmpl.append(-1) self.val.append(tmpl) tmpl=[] for t in range(self.nbtextes): tmpl.append(u"") self.txtval.append(tmpl) self.majval() self.nblig+=1 #self.setlvisu(self.lvisu+1) #self.chglcourant(self.lcourant+1) def prevalvisu(self, lvisu=None, initial=False): for lig in range(self.nbligvisu): for i in range(self.nbchamps): try: win32gui.SetWindowText(self.h[lig][i].hwnd, '') except: pass for i in range(self.nbtextes): self.htxt[lig][i].texte=u"" win32gui.PumpWaitingMessages() def valvisu(self, lvisu=None, initial=False): """ lvisu est le num de ligne absolue qui correspond à 1ere ligne visualisée """ if lvisu is None: lvisu=self.lvisu if self.lvisu != lvisu: self.chglcourant(self.lcourant+(lvisu-self.lvisu)) self.lvisu = lvisu nlig=min(self.nbligvisu,len(self.val)) """ print for j,i in enumerate(self.val): print 8300,j,i print """ """ for nlig,lval in enumerate(self.val[self.lvisu:]): if nlig>=self.nbligvisu: break for i,v in enumerate(lval): if i self.nbligvisu-1: break for i,v in enumerate(lval): try: if self.htxt[nligt][i].texte!=v: self.htxt[nligt][i].texte=v except: pass """ self.w.grainsdeselflag=999 nlig=-1 for lval,tval in zip(self.val[self.lvisu:],self.txtval[self.lvisu:]): nlig+=1 if nlig>=self.nbligvisu: break for i,v in enumerate(lval): if i<=self.nbchamps: #print 8559,self.h[nlig][i].fast1lirecontenu(format=self.chl[i].format) try: #print 8561, type(self.h[nlig][i].fast1lirecontenu(format=self.chl[i].format)) #print 8561," ",i,self.chl[i].format #print 8562, v, self.h[nlig][i].fast1lirecontenu(format=self.chl[i].format) if v!=self.h[nlig][i].fast1lirecontenu(format=self.chl[i].format): self.h[nlig][i].fastset(v,format=self.chl[i].format) except: pass for i,v in enumerate(tval): try: self.w.majtextseul(self.htxt[nlig][i],v) except: pass if nlig0: if self.lvisu0: nnb=nb if nnb != 0: self.chglcourant(self.lcourant+nnb) self.lvisu += nnb self.valvisu() @staticmethod def gmdeletelig(w,el,key,*suite): """ supprime la ligne ligne """ global DEBUGFLAG if key == 'KEY_Alt+': nb_return=0 while win32api.GetAsyncKeyState(win32con.VK_DELETE) & 0x8000: time.sleep(0.01) nb_return+=1 if nb_return>19: break hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe lig=cfocus.ligne+hgroupe.lvisu numdanslig=cfocus.numdanslig try: del(hgroupe.val[lig]) del(hgroupe.txtval[lig]) except: return #w.ctrlfocus(cfocus) hgroupe.nblig-=1 hgroupe.w.ligcourante=lig if lig < hgroupe.nblig-1: #mg_ligne.suitup(w,el,key,*suite) hgroupe.lcourant=hgroupe.nblig-1 hgroupe.w.ligcourante=hgroupe.nblig-1 hgroupe.valvisu() """ buffer_key=w.grainsdesel w.grainsdesel={} hgroupe.valvisu() w.grainsdesel=buffer_key """ w.ctrlfocus(cfocus) @staticmethod def gminsertlig(w,el,key,*suite): """ insère une ligne """ if key == 'KEY_Alt+': nb_return=0 while win32api.GetAsyncKeyState(win32con.VK_INSERT) & 0x8000: time.sleep(0.01) nb_return+=1 if nb_return>19: break hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe lig=cfocus.ligne+hgroupe.lvisu+1 numdanslig=cfocus.numdanslig #hgroupe.majval() tmpl=[] for c in range(hgroupe.nbchamps): tmpl.append(u"") tmpl.append(-1) hgroupe.val.insert(lig-1,tmpl) tmpl=[] for t in range(hgroupe.nbtextes): tmpl.append(u"") hgroupe.txtval.insert(lig-1,tmpl) hgroupe.nblig+=1 hgroupe.valvisu(hgroupe.lvisu) """ buffer_key=w.grainsdesel w.grainsdesel={} hgroupe.valvisu(hgroupe.lvisu) w.grainsdesel=buffer_key """ w.ctrlfocus(cfocus) @staticmethod def suitdown(w,el,typevent,*suite): hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe try: lig=cfocus.ligne+1 numdanslig=cfocus.numdanslig except: pass else: if w.multigroup is not None: hgroupe=w.multigroup lig=1 numdanslig=0 win32gui.SendMessage( w.getfocus().hwnd, win32con.EM_SETSEL, 0, 35) if hgroupe is not None: if lig>=min(hgroupe.nbligvisu,hgroupe.nblig+1): # 01.12.2011 : ajout du "+1" toujours utile ? #w.grainsdeselflag=999 hgroupe.scroll(1) #w.grainsdeselflag=0 else: hgroupe.lcfocus(lig,numdanslig) win32gui.SendMessage( w.getfocus().hwnd, win32con.EM_SETSEL, 0, 35) @staticmethod def suitup(w,el,typevent,*suite): hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe try: lig=cfocus.ligne-1 numdanslig=cfocus.numdanslig except: pass else: if w.multigroup is not None: hgroupe=w.multigroup lig=1 numdanslig=1 win32gui.SendMessage( w.getfocus().hwnd, win32con.EM_SETSEL, 0, 35) if hgroupe is not None: if lig<0: hgroupe.scroll(-1) else: hgroupe.lcfocus(lig,numdanslig) win32gui.SendMessage( w.getfocus().hwnd, win32con.EM_SETSEL, 0, 35) """ for i in range(8): time.sleep(0.02) # win32gui.PumpWaitingMessages() """ @staticmethod def suitpagedown(w,el,typevent,*suite): hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe try: lig=cfocus.ligne+1 numdanslig=cfocus.numdanslig except: pass else: if w.multigroup is not None: hgroupe=w.multigroup lig=1 numdanslig=1 hgroupe.lcfocus(0,1) if hgroupe is not None: if hgroupe.nblig>hgroupe.nbligvisu: newlvisu = hgroupe.lvisu+hgroupe.nbligvisu if newlvisu>(hgroupe.nblig-hgroupe.nbligvisu): newlvisu=hgroupe.nblig-hgroupe.nbligvisu lig=hgroupe.lcourant + (newlvisu-hgroupe.lvisu) else: lig=hgroupe.lcourant + hgroupe.nbligvisu hgroupe.chglcourant(lig, tmplvisu=newlvisu) hgroupe.setlvisu(newlvisu) #hgroupe.valvisu() #time.sleep(0.1) for i in range(0): #16): time.sleep(0.01) win32gui.PumpWaitingMessages() @staticmethod def suitpageup(w,el,typevent,*suite): hgroupe=None cfocus=w.getfocus() if hasattr(cfocus,"ogroupe"): hgroupe=cfocus.ogroupe try: lig=cfocus.ligne+1 numdanslig=cfocus.numdanslig except: pass else: if w.multigroup is not None: hgroupe=w.multigroup lig=1 numdanslig=1 hgroupe.lcfocus(0,1) if hgroupe is not None: if hgroupe.nblig>hgroupe.nbligvisu: newlvisu = hgroupe.lvisu-hgroupe.nbligvisu if newlvisu<0: newlvisu=0 lig = hgroupe.lcourant - hgroupe.lvisu else: lig = hgroupe.lcourant - hgroupe.nbligvisu hgroupe.chglcourant(lig, tmplvisu=newlvisu) hgroupe.setlvisu(newlvisu) for i in range(0): #16): time.sleep(0.01) win32gui.PumpWaitingMessages() @staticmethod def suithome(w,el,key,*suite): if key=='KEY_Ctrl+': cfocus=w.getfocus() hgroupe=cfocus.ogroupe hgroupe.focusdebutdeb() hgroupe.chglcourant(0) for i in range(9): time.sleep(0.01) win32gui.PumpWaitingMessages() @staticmethod def suitend(w,el,key,*suite): if key=='KEY_Ctrl+': try: cfocus=w.getfocus() hgroupe=cfocus.ogroupe if hgroupe.nblig>hgroupe.nbligvisu: ###hgroupe.lvisu=hgroupe.nblig-hgroupe.nbligvisu #hgroupe.setlvisu(hgroupe.nblig-hgroupe.nbligvisu) #, newligne=hgroupe.nblig) hgroupe.focusfinder() hgroupe.setlvisu(hgroupe.nblig-hgroupe.nbligvisu) #, newligne=hgroupe.nblig) win32gui.PumpWaitingMessages() #print 6927,hgroupe.nblig,hgroupe.nbligvisu,hgroupe.nblig-hgroupe.nbligvisu else: hgroupe.lcfocus(hgroupe.nblig-1,hgroupe.nbchamps-1) hgroupe.chglcourant(hgroupe.nblig-1) for i in range(9): time.sleep(0.01) win32gui.PumpWaitingMessages() except: pass else: try: cfocus=w.getfocus() if not hasattr(cfocus,"ogroupe"): if w.multigroup is not None: hgroupe=w.multigroup lig=1 numdanslig=0 if hgroupe.nblig>hgroupe.nbligvisu: hgroupe.focusfinder() hgroupe.setlvisu(hgroupe.nblig-hgroupe.nbligvisu) #, newligne=hgroupe.nblig) win32gui.PumpWaitingMessages() else: hgroupe.lcfocus(hgroupe.nblig-1,hgroupe.nbchamps-1) hgroupe.chglcourant(hgroupe.nblig-1) for i in range(9): time.sleep(0.01) win32gui.PumpWaitingMessages() except: pass @staticmethod def suivivalid(w,el,typevent,*suite): if typevent=="COMMAND": pass #hgroupe=el.ogroupe #labsolue=el.ligne+hgroupe.lvisu elif typevent=="QUITTED": hgroupe=suite[0][0].ogroupe labsolue=suite[0][0].ligne+hgroupe.lvisu #on quitte suite[0][0] #on arrive sur suite[0][1] if labsolue>=hgroupe.nblig: hgroupe.gmajoutlig() if labsolue>=hgroupe.nblig and el==hgroupe.h[0][0] or el==w.edits[w.ledits[0]]: if hgroupe.nblig>hgroupe.nbligvisu: #à voir 03.12.2011 hgroupe.majval(labsolue) hgroupe.gmajoutlig() hgroupe.lvisu+=1 hgroupe.valvisu(hgroupe.nblig-hgroupe.nbligvisu) hgroupe.focusdebutder() elif suite[0][0].ligne != suite[0][1].ligne: if hgroupe.nblig<=labsolue: hgroupe.gmajoutlig() hgroupe.majval(labsolue) #suite[0][0].ligne) class mg_champ(object): """ champs d'une "ligne" d'un multi-groupes """ def __init__(self, label, x,y, larg,haut, multiligne=False, border=False, mlscroll=False, font='DEFAULT', textcolor=(0,0,0), align="LEFT", format=0, valeur=u""): """ Si label is None, pas d'affichage du label valeur = valeur initiale """ self.label=label self.valeur=valeur self.x=x self.y=y self.l=larg self.h=haut self.font=font self.border=border self.multiligne=multiligne self.mlscroll=mlscroll self.align=align self.format=format self.textcolor=textcolor class mg_texte(object): """ textes d'une "ligne" d'un multi-groupes """ def __init__(self, texte="Texte", x=None,y=None,l=None,h=None, multiligne=False, font=None, textcolor=(192,0,0), backcolor=None, align='LEFT', valign='TOP'): """ Si label is None, pas d'affichage du label valeur = valeur initiale """ self.texte=texte self.x=x self.y=y self.l=l self.h=h self.multiligne=multiligne self.font=font self.textcolor=textcolor self.backcolor=backcolor self.align=align self.valign=valign def gmchoixvlist(dataliste, nbcols=2, colselection=1,largeurs=[80,300], nbligs=[12], titres=['Compte',u'Descriptif'],aligns=['LEFT','LEFT'], fond=(205,255,255), mode="AUTO1", formats=[0]*99, recarrivee=None): """ Choisir dans une liste de liste mode="AUTO1" ; validation automatique, lorsqu'il reste un seul élément mode="NORMAL" ; la validation sera manuelle ({Entrée} ou bouton) """ largeur=100 for i in largeurs: largeur += i winlargeur=max(580,int(largeur)) winhauteur=nbligs*31+90 if not (type(colselection) in (types.ListType,types.TupleType)): if colselection<0: colselection=range(1-colselection) w=win(u"Sélection / recherche") w.setprop(x=-1,y=-1,l=winlargeur,h=winhauteur) w.setprop(fond=fond) w.setprop(CAPTION=True, SYSMENU=True, THICKFRAME=False) if dataliste==[]: ltmp=[] for i in range(len(titres)): ltmp.append("") dataliste.append(ltmp) for i in dataliste: if not isinstance(i[0], (basestring,unicode)): if i[0] is None: i[0]="" else: i[0]=unicode(str(i[0]).decode('cp1252','ignore')) if not isinstance(i[0], unicode): i[0]=unicode(i[0]) if len(i)>1: if not isinstance(i[1], (basestring,unicode)): if i[1] is None: i[1]="" else: i[1]=unicode(str(i[1]).decode('cp1252','ignore')) #if not isinstance(i[1], unicode): # i[1]=unicode(i[1]) champselection = w.add_edit(80,10,100,20, False) w.add_label(u" Sélection ",10,10,70,20) if mode=="NOUVIDE": btnouv = w.add_bouton("Nouveau(vide){N}",230,5,120,30) else: btaide = w.add_bouton("Aide {F1}",270,5,80,30) btok = w.add_bouton(u"Valide {Entrée}",350,5,110,30) btquit= w.add_bouton("Abandon {Echap}",460,5,110,30) def fboutonaide(w,el,typevent,*suite): ww=win(u"Aide sur Sélection / recherche") ww.setprop(x=-1,y=-1,l=540+6,h=420) ww.setprop(CAPTION=True, SYSMENU=True, THICKFRAME=False) ww.add_text(texte=u""" Dans le champ sélection, saisir un contenu à chercher Utiliser les flèches (haut / bas) pour finir la sélection {Entrée} valide la ligne en cours (1ère ligne, si pas de sélection) {Echap} abandonne Compléments: La sélection est une expression régulière L'affichage est mis à jour de façon incrémentale Les boutons ont la même valeur que les touches.""",x=40,y=40,l=440,h=400,multiligne=True) ww.graindesel( btok,ww.ferme) ww.graindeselkey( VK_RETURN=ww.ferme, VK_ESCAPE=ww.ferme) ww.define() ww.run() return False def fboutonok(w,el,typevent,*suite): #if typevent.startswith("KEY_"): if True: cfocus=w.getfocus() if cfocus==champselection: w.ligcourante=None if w.ligcourante is None: try: vret=gmchoixvlist.lcourante[obj_lig.lvisu] except: vret=None else: #print 8882,obj_lig.lcourant if w.ligcourante != obj_lig.lcourant: w.ligcourante = obj_lig.lcourant if w.ligcourante<0: vret=None else: try: vret=gmchoixvlist.lcourante[w.ligcourante] except: vret=None w.ferme() # vret contient la ligne sélectionnée, ou None si abandon def fboutonnouv(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus!=champselection: w.ligcourante=-2 vret=-2 #-1 pour Nouveau/vide w.ferme() else: return False def fboutonabandon(w,el,typevent,*suite): w.ligcourante=-1 vret=None w.ferme() # vret contient la ligne sélectionnée, ou None si abandon def suitabchoixvl(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: obj_lig.lcfocus(1,0) else: w.ctrlfocus(champselection) obj_lig.valvisu(lvisu=0) time.sleep(0.1) w.ctrlfocus(champselection) time.sleep(0.1) def suitdownchoixvl(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: obj_lig.lcfocus(2,0) time.sleep(0.1) def suitendchoixvl(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: obj_lig.lcfocus(1,len(gmchoixvlist.lcourante)-1) time.sleep(0.1) def suivi_champ01(w,el,typevent,*suite): if typevent=="QUITTED": pass else: if suite[0] is not None: try: if suite[0][1].numdanslig==0 or suite[0][1].numdanslig==1: #on vient de suite[0][0] pour arriver sur suite[0][1] hgroupe=suite[0][1].ogroupe ligabsolue=suite[0][1].ligne+hgroupe.lvisu contenu=suite[0][1].fast1lirecontenu() #print 8953,contenu,ligabsolue,' ',hgroupe.lcourant if hgroupe.lcourant != ligabsolue: hgroupe.lcourant = ligabsolue except: pass def suiviselection(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: try: obj_lig.blanclcourant() crit=str(w.gettext(el)) crit=crit.replace('\t','') crit=crit.replace(chr(0),'') crit=crit.replace('\r','') crit=crit.replace('\n','') crit=crit.replace(',','.*') crit=crit.rstrip() recritere=re.compile(crit,re.IGNORECASE) except: return gmchoixvlist.lcourante=[] if type(colselection) in (types.ListType,types.TupleType): def slescol(rcrit, i): flag=False for num in colselection: try: if rcrit.search(i[num]): flag=True break except: flag=True return flag gmchoixvlist.lcourante=[i for i in dataliste if slescol(recritere,i)] elif colselection<0: def stoutescol(rcrit, i): flag=False for item in i: try: if rcrit.search(item): flag=True break except: flag=True return flag gmchoixvlist.lcourante=[i for i in dataliste if stoutescol(recritere,i)] else: ''' gmchoixvlist.lcourante=[] for i in dataliste: try: if recritere.search(i[colselection]): gmchoixvlist.lcourante.append(i) except: pass ''' try: gmchoixvlist.lcourante=[i for i in dataliste if recritere.search(i[colselection])] except: return if nbcols != len(dataliste[0]): datavisu=[ l[0:nbcols] for l in gmchoixvlist.lcourante] else: datavisu=gmchoixvlist.lcourante obj_lig.toutesvaleurs(datavisu,nblignes=len(gmchoixvlist.lcourante)) obj_lig.valvisu(lvisu=0) if mode=="AUTO1": if len(gmchoixvlist.lcourante)==1: fboutonok(w,el,typevent,suite) else: pass """ try: tempval=cfocus.fast1lirecontenu() #tempval=cfocus.contenu() #print 9011,tempval num=-1 for lig,i in enumerate(gmchoixvlist.lcourante): if tempval in i: num=lig break #print 9018,num if num>-1: if cfocus.ogroupe.lcourant != num: cfocus.ogroupe.lcourant = num except: pass """ if mode=="NOUVIDE": w.graindesel( btnouv,fboutonnouv, btok,fboutonok, btquit,fboutonabandon, champselection,suiviselection) #w.graindeselkey( N=fboutonnouv, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitabchoixvl, VK_DOWN=suitdownchoixvl, VK_NEXT=suitdownchoixvl, VK_END=suitendchoixvl) w.graindeselkey( N=fboutonnouv, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitabchoixvl, VK_END=suitendchoixvl) else: w.graindesel( btaide,fboutonnouv, btok,fboutonok, btquit,fboutonabandon, champselection,suiviselection) #w.graindeselkey( VK_F1=fboutonaide, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitabchoixvl, VK_DOWN=suitdownchoixvl, VK_NEXT=suitdownchoixvl, VK_END=suitendchoixvl) w.graindeselkey( VK_F1=fboutonaide, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitabchoixvl, VK_END=suitendchoixvl) ###w.graindeselkey( VK_F1=fboutonaide, VK_ESCAPE=fboutonabandon, VK_TAB=suitabchoixvl, VK_END=suitendchoixvl) w.add_font("CHAMPTXT","Arial Narrow", 25) tchamps=[] x=5 n=0 for largeur,titre,align,form in zip(largeurs,titres,aligns,formats): tchamps.append(mg_champ(None,x,3, largeur,28, multiligne=False, border=False, format=form, font="CHAMPTXT")) x=x+largeur+5 n+=1 if n>=nbcols: break if isinstance(nbligs,list): nbligmax=nbligs[0]-1 else: nbligmax=nbligs obj_lig=mg_ligne(nbligmax, len(dataliste), 35,50, x+40,31, tchamps,[],flagdessin=False) #obj_lig.surlignage=True obj_lig.visu(w) """ for l in dataliste: if isinstance( l[0], basestring): try: l[0]=l[0].decode('utf-8','ignore') except: print type(l[0]) print l[0] if isinstance( l[1], basestring): try: l[1]=l[1].decode('utf-8','ignore') except: print type(l[1]) print l[1] """ if nbcols != len(dataliste[0]): datavisu=[ l[0:nbcols] for l in dataliste] else: datavisu=dataliste obj_lig.toutesvaleurs(datavisu) obj_lig.graindesel(w, 0, suivi_champ01) if colselection!=0: obj_lig.graindesel(w, 1, suivi_champ01) w.define(auto=None) w.setedittext(champselection,"") nbk=0 win32gui.PumpWaitingMessages() while win32api.GetAsyncKeyState(win32con.VK_SPACE) & 0x8000: win32gui.PumpWaitingMessages() nbk+=1 if nbk>5: break time.sleep(0.02) #obj_lig.valvisu(initial=False) w.ctrlfocus(champselection) try: obj_lig.lvisu=0 if recarrivee>obj_lig.nbligvisu: try: obj_lig.lvisu = int((recarrivee)/obj_lig.nbligvisu)*obj_lig.nbligvisu except: pass obj_lig.valvisu(lvisu=obj_lig.lvisu) obj_lig.lcfocus(recarrivee-obj_lig.lvisu,0) except: pass msg = MSG() ktime=time.time() while (time.time()-ktime)<0.25: if win32api.GetAsyncKeyState(32) & 0x8000: if ctypes.windll.user32.PeekMessageA(ctypes.pointer(msg), self.hwnd, 0, 0, 0): ctypes.windll.user32.GetMessageA(ctypes.pointer(msg), self.hwnd, 0, 0) time.sleep(0.001) else: break w.run() # w.ligcourante contient la dernière ligne courante if w.ligcourante is None: try: vret=gmchoixvlist.lcourante[obj_lig.lvisu] except: vret=None else: if w.ligcourante == -2: vret=-2 elif w.ligcourante<0: vret=None else: try: vret=gmchoixvlist.lcourante[w.ligcourante] except: vret=None # vret contient la ligne sélectionnée, ou None si abandon return vret def gettop(*p): """ retourne le handle de la fenêtre au premier plan """ try: htemp=win32gui.GetForegroundWindow() except: htemp=None return htemp def hvalideactivex(duree=1): import win32gui,win32con,time hvalideactivex.htrouve=None def traitefenetres(h, titre=""): txt=win32gui.GetWindowText(h) if txt.find("Avertissement")>-1 and txt.find("Windows")>-1: time.sleep(0.05) #win32gui.SetForegroundWindow(h) hvalideactivex.htrouve=h for i in range(duree*9): time.sleep(0.1) win32gui.EnumWindows(traitefenetres, u"Titre") if hvalideactivex.htrouve is not None: #win32gui.SetForegroundWindow(hvalideactivex.htrouve) #time.sleep(0.01) #win32gui.SetActiveWindow(hvalideactivex.htrouve) #time.sleep(0.01) """ x,y,l,h = win32gui.GetWindowRect(hvalideactivex.htrouve) #print 89,x,y,l,h,win32gui.GetWindowText(hvalideactivex.htrouve) win32gui.MoveWindow(hvalideactivex.htrouve, 0,0, l-x,h-y,1 ) time.sleep(0.01) win32gui.ShowWindow(hvalideactivex.htrouve, win32con.SW_SHOWNORMAL) time.sleep(0.01) win32gui.SetForegroundWindow(hvalideactivex.htrouve) """ time.sleep(1.1) keyvkcode("VK_LEFT") time.sleep(0.50) keyvkcode("VK_RETURN") time.sleep(1.1) #keyvkcode("VK_SPACE") #time.sleep(0.05) return def find_window(parent, names): """ Trouve une fenêtre fille d'une fenêtre """ if not names: return parent name = unicode(names[0]) child = 0 while True: child = ctypes.windll.user32.FindWindowExW(parent, child, name, 0) if not child: return 0 result = find_window(child, names[1:]) if result: return result def trouvebureau(): desktop = ctypes.windll.user32.GetDesktopWindow() handle = 0 handle = handle or find_window(desktop, ['Progman', 'SHELLDLL_DefView', 'SysListView32']) handle = handle or find_window(desktop, ['WorkerW', 'SHELLDLL_DefView', 'SysListView32']) return handle def editfichier(fichier=os.getcwd()+"\\f_data.txt", data="", taillemaxi=None, encodage=''): """ mini-éditeur de fichier texte. Si fichier is None, édition de texte en mémoire (data). Si le fichier n'existe pas, il est créé. taillemaxi = 30000 par défaut (valeur Windows) """ editfichier.valeurachercher="" if fichier is None: editfichier.dataorigine=data else: if not os.path.isfile(fichier): open(fichier,"wb").write(data) time.sleep(0.01) if encodage=='': editfichier.dataorigine=open(fichier,"rb").read() else: editfichier.dataorigine=open(fichier,"rb").read().decode(encodage,'ignore') def chercher(w, *suite): vret=inputbox(titre="(re)-Chercher", texte=u"Chercher :", valeurinit=editfichier.valeurachercher) if vret is not None: if vret != '': editfichier.valeurachercher=vret position=w.ctrlselection(ch)[0]+1 data=ch.contenu() i=data.find(editfichier.valeurachercher,position) if i>-1: w.ctrlfocus(ch) w.ctrlselection(ch,i,i+len(editfichier.valeurachercher)) else: alert(editfichier.valeurachercher,u"non trouvé.") w.active() w.ctrlfocus(ch) def ctrl_f(w, *suite): if suite[1]=='KEY_Ctrl+': chercher(w) def resume(w, *suite): r=u"" data=ch.contenu() r+=u"Nb caractères : "+str(len(data)) if encodage == '': data=ch.contenu() else: data=ch.contenu().decode('cp1252','ignore') if data != editfichier.dataorigine: r+=u"\r\nModifié : Oui" else: r+=u"\r\nModifié : Non" if fichier is not None: r+=u"\r\nFichier : "+fichier tai,nblig,ligne = ch.statistics() r+=u"\r\nNb lignes : "+str(nblig) r+=u"\r\nLigne courante : "+str(ligne) temp = ch.selection() r+=u"\r\nLongueur ligne courante: "+str(ch.linelongueur(temp[0])) r+=u"\r\nPosition (n°car): "+str(temp[0]) r+=u"\r\nn° du 1er car. de la Ligne courante : "+str(ch.carindexline(ligne)) temp=ch.getpositionchar() r+=u"\r\nPosition X,Y du curseur: "+str(temp[0])+','+str(temp[1]) r+=u"\r\n1ère ligne visible: "+str(ch.firstvisibleline()) alert(u"Résumé",r) w.active() w.ctrlfocus(ch) time.sleep(0.250) def undoredo(w, *suite): """ Annule/refait la dernière modification """ ch.undoredo() def cherchersuivant(w, *suite): if editfichier.valeurachercher != '': position=w.ctrlselection(ch)[0]+1 data=ch.contenu() i=data.find(editfichier.valeurachercher,position) if i>-1: w.ctrlfocus(ch) w.ctrlselection(ch,i,i+len(editfichier.valeurachercher)) else: alert(editfichier.valeurachercher,u"non trouvé.") w.active() w.ctrlfocus(ch) time.sleep(0.250) def annulmodif(w, *suite): ch.contenu(editfichier.dataorigine) def aller(w, *suite): vret=inputbox(titre=u"Va au caractère...", texte=u"Position :") if vret != '': w.ctrlfocus(ch) w.ctrlselection(ch, int(vret)) def ouvremenu(w, *suite): w.callmenu() def quitter(w, *suite): w.calcresult() if fichier is not None: if encodage == '': data=ch.contenu() else: data=ch.contenu().decode('cp1252','ignore') if data != editfichier.dataorigine: reponse=popup(text=u"Enregistrer les modifs ?", nbsec=5, title=u"Données modifiées", typ=4) if reponse==6: if encodage != '': data=data.encode(encodage,'ignore') open(fichier,"wb").write(data) w.ferme() def enregistrer(w, *suite): if encodage == '': data=ch.contenu() else: data=ch.contenu().decode('cp1252','ignore') editfichier.dataorigine=data if encodage != '': data=data.encode(encodage,'ignore') open(fichier,"wb").write(data) w=win(u"Multi-lignes") w.x=-1 w.y=-1 w.l=900 w.h=600 smenu=u""" 9101 &Quitter ou abandonner """ if fichier is not None: smenu += u""" 9102 &Enregistrer """ smenu += u""" 9103 &UnDO ReDO 9104 &Annuler modifs depuis enregistrement 9105 &Résumé 9109 ---- 9110 &Chercher {Ctrl-F} 9111 &Suivant (chercher) {F3} 9112 &Va au caractère n°... DEFAULT:9101 """ w.createmenu(contextmenu=smenu) w.graindesel(9101,quitter, 9102,enregistrer, 9103,undoredo, 9104,annulmodif, 9105,resume, 9110,chercher, 9111,cherchersuivant, 9112,aller) w.graindeselkey( VK_F3=cherchersuivant, F=ctrl_f) w.add_font(code="EDITFICHIER", nom="Courier new", taille=18, gras=False, italique=0, souligne=0) ch=w.add_edit(x=0,y=29,l=w.l-(metric.SM_CXSIZEFRAME)*2,h=w.h-30-(metric.SM_CYSIZEFRAME)*2-metric.SM_CYCAPTION,multiligne=True, font="EDITFICHIER") btmenu=w.add_bouton(texte="{Echap} Menu",x=0,y=0, l=100,h=28, fonction=ouvremenu) w.define(auto="NO") if taillemaxi is not None: ch.longmax(taillemaxi) w.ctrlfocus(ch) ch.contenu(editfichier.dataorigine) w.run() vret='\r\n'.join(w.result[2001]) return vret def choixvlist(dataliste, colselection=1,largeurs=[60,200], nbligs=[1], titres=['Code',u'Nom du département'],aligns=['LEFT','LEFT'], fond=(205,255,255), mode="AUTO1"): """ Choisir dans une liste de liste mode="AUTO1" ; validation automatique, lorsqu'il reste un seul élément mode="NORMAL" ; la validation sera manuelle ({Entrée} ou bouton) """ largeur=0 for i in largeurs: largeur += i winlargeur=max(560,(int(largeur/100)+1)*100) winhauteur=520 w=win(u"Sélection / recherche") w.setprop(x=-1,y=-1,l=winlargeur,h=winhauteur) w.setprop(fond=fond) w.setprop(CAPTION=True, SYSMENU=True, THICKFRAME=False) if dataliste==[]: ltmp=[] for i in range(len(titres)): ltmp.append("") dataliste.append(ltmp) lcourante=dataliste[:] lvid = w.add_vlist(int((winlargeur-largeur)/2)-10,40,largeur+20,winhauteur-80,largeurs,aligns,titres,lcourante) champselection = w.add_edit(80,10,100,20, False) w.add_label(u" Sélection ",10,10,70,20) if mode=="NOUVIDE": btnouv = w.add_bouton("Nouveau(vide){N}",180,5,120,30) else: btaide = w.add_bouton("Aide {F1}",220,5,80,30) btok = w.add_bouton(u"Valide {Entrée}",300,5,120,30) btquit= w.add_bouton("Abandon {Echap}",420,5,120,30) def fboutonaide(w,el,typevent,*suite): ww=win(u"Aide sur Sélection / recherche") ww.setprop(x=-1,y=-1,l=540+6,h=420) ww.setprop(CAPTION=True, SYSMENU=True, THICKFRAME=False) ww.add_text(texte=u""" Dans le champ sélection, saisir un contenu à chercher Utiliser les flèches (haut / bas) pour finir la sélection {Entrée} valide la ligne en cours (1ère ligne, si pas de sélection) {Echap} abandonne Compléments: La sélection est une expression régulière L'affichage est mis à jour de façon incrémentale Les boutons ont la même valeur que les touches.""",x=40,y=40,l=440,h=400,multiligne=True) ww.graindesel( btok,ww.ferme) ww.graindeselkey( VK_RETURN=ww.ferme, VK_ESCAPE=ww.ferme) ww.define() ww.run() def fboutonok(w,el,typevent,*suite): if w.ligcourante is None: try: vret=choixvlist.lcourante[0] except: vret=None else: if w.ligcourante<0: vret=None else: try: vret=choixvlist.lcourante[w.ligcourante] except: vret=None w.ferme() # vret contient la ligne sélectionnée, ou None si abandon def fboutonnouv(w,el,typevent,*suite): w.ligcourante=-2 vret=-2 #-1 pour Nouveau/vide w.ferme() def fboutonabandon(w,el,typevent,*suite): w.ligcourante=-1 vret=None w.ferme() # vret contient la ligne sélectionnée, ou None si abandon def suitab(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: w.ctrlfocus(lvid) w.lvgoitem(lvid,1) else: w.ctrlfocus(champselection) def suitdown(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: w.ctrlfocus(lvid) w.lvgoitem(lvid,1-1) # -1 car le {DOWN} n'est pas intercepté def suitend(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: w.ctrlfocus(lvid) w.lvgoitem(lvid,len(choixvlist.lcourante)-1) def suiviselection(w,el,typevent,*suite): crit=str(w.gettext(el)) crit=crit.replace('\t','') crit=crit.replace(chr(0),'') crit=crit.replace('\r','') crit=crit.replace('\n','') crit=crit.rstrip() recritere=re.compile(crit,re.IGNORECASE) #choixvlist.lcourante=[i for i in dataliste if recritere.search(i[colselection])] choixvlist.lcourante=[] for i in dataliste: try: if recritere.search(i[colselection]): try: choixvlist.lcourante.append(i) except: pass except: pass w.replacelliste(lvid, choixvlist.lcourante) if mode=="AUTO1": if len(choixvlist.lcourante)==1: fboutonok(w,el,typevent,suite) if mode=="NOUVIDE": w.graindesel( btnouv,fboutonnouv, btok,fboutonok, btquit,fboutonabandon, champselection,suiviselection) w.graindeselkey( N=fboutonnouv, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitab, VK_DOWN=suitdown, VK_NEXT=suitdown, VK_END=suitend) else: w.graindesel( btaide,fboutonnouv, btok,fboutonok, btquit,fboutonabandon, champselection,suiviselection) w.graindeselkey( VK_F1=fboutonaide, VK_RETURN=fboutonok, VK_ESCAPE=fboutonabandon, VK_TAB=suitab, VK_DOWN=suitdown, VK_NEXT=suitdown, VK_END=suitend) w.define(auto=None) w.visulliste(lvid) w.ctrlfocus(champselection) w.run() # w.ligcourante contient la dernière ligne courante if w.ligcourante is None: try: vret=choixvlist.lcourante[0] except: vret=None else: if w.ligcourante == -2: vret=-2 elif w.ligcourante<0: vret=None else: try: vret=choixvlist.lcourante[w.ligcourante] except: vret=None # vret contient la ligne sélectionnée, ou None si abandon return vret def gestion(mode="TOUS", ldata=[[]], labels=[], largeur=600, hauteur=400, glargeurs=[100], gnbligs=[20], fond=(205,220,220)): if ldata==[]: ltmp=[] for i in range(len(labels)): ltmp.append("") ldata.append(ltmp) try: valarrivee=ldata[0] except: valarrivee="" nbch = len(labels) # nb champs bufch = [None] * nbch idch = [None] * nbch while valarrivee is not None: valarrivee = choixvlist(ldata, colselection=1, largeurs=[80,320], titres=[labels[0],labels[1]], fond=fond, mode="NOUVIDE") if valarrivee is not None: def fboutonenregistre(ww,id,typevent, *suite): for i in range(nbch): bufch[i]=idch[i].contenu() if mode=="CLEF": if bufch[0] != valarrivee[0]: ww.alert(u"Problème", u"""Pour [Enregistrer], il ne faut pas modifier la clef""") return for n,i in enumerate(ldata): flag=True for j in range(nbch): if i[j] != valarrivee[j]: flag=False break if flag: ldata[n]=[v for v in bufch] ww.ferme() def fboutoncree(ww,id,typevent, *suite): for i in range(nbch): bufch[i]=idch[i].contenu() if mode=="CLEF": flag=False for n,i in enumerate(ldata): if i[0] == bufch[0]: flag=True break if flag: ww.alert(u"Impossible de [Créer]", u"La clef ("+str(bufch[0])+u") existe déjà") return ldata.append([v for v in bufch]) ww.ferme() def fboutonnouv(ww,id,typevent, *suite): for i in range(nbch): bufch[i]=idch[i].contenu() if mode=="CLEF": flag=False for n,i in enumerate(ldata): if i[0] == bufch[0]: flag=True break if flag: ww.alert(u"La clef ("+str(bufch[0])+u") existe déjà", u"Impossible de [Créer]") return ldata.append([v for v in bufch]) for i in range(nbch): idch[i].contenu("") idch[0].focus() time.sleep(0.250) def fboutonsupprime(ww,id,typevent, *suite): for i in range(nbch): bufch[i]=idch[i].contenu() for n,i in enumerate(ldata): flag=True for j in range(nbch): if i[j] != valarrivee[j]: flag=False break if flag: del ldata[n] ww.ferme() def suivichamp(ww,el,typevent,*suite): """ if typevent=="QUITTED": print "On vient de quitter le champ2 (pour aller sur",suite[0][1].id,")" else: if suite[0] is not None: print "On vient d'arriver sur le champ2, en venant de",suite[0][0].id print el.id," champ-2:", el.contenu()[0] """ pass #if len(labels)>11: # hauteur += (len(labels)-11)*25 ww=win(u"Fenêtre & Champs", x=-1,y=-1, l=largeur,h=hauteur) ww.setprop(fond=fond) if valarrivee == -2: ww.createmenu(contextmenu=u""" 9100 rien (fermer le menu) 9102 &Créer + quitter 9103 Créer + &Nouveau 9109 &Quitter ou Abandonner """) else: ww.createmenu(contextmenu=u""" 9100 rien (fermer le menu) 9101 &Enregistrer 9102 &Créer 9103 &Supprimer 9109 &Quitter ou Abandonner """) for i in range(len(labels)): try: llarg=glargeurs[i] except: llarg=120 try: nblig=gnbligs[i] except: nblig=20 if nblig>20: mlig=True else: mlig=False #idch[i] = ww.add_edit(int((largeur-glargeurs[0])/2)+20,None, llarg, nblig, mlig) idch[i] = ww.add_edit(120+20,None, llarg, nblig, mlig) #llargeur=len(labels[0])*8 llargeur=120 for i in range(len(labels)): #ww.add_label(labels[i],int((largeur-glargeurs[0])/2)-llargeur, i*25+40, llargeur+20) ww.add_label(labels[i],20, i*25+21, llargeur, 18) y = ww.h-(win32api.GetSystemMetrics(win32con.SM_CYFRAME)+ \ win32api.GetSystemMetrics(win32con.SM_CYCAPTION)+ \ win32api.GetSystemMetrics(win32con.SM_CYFRAME)+30) x=int((ww.l-100*4)/2-win32api.GetSystemMetrics(win32con.SM_CXFRAME)*2) if valarrivee == -2: btcree = ww.add_bouton(u"Créer + quitter",x+60,y, 120,30) btnouv = ww.add_bouton(u"Créer + Nouveau",x+180,y, 120,30) btquit= ww.add_bouton("Abandonner",x+300,y, 120,30) ww.graindesel(btcree,fboutoncree, btnouv,fboutonnouv, btquit,ww.ferme) ww.graindesel(9102,fboutoncree, 9103,fboutonnouv, 9109,ww.ferme) else: btenregistre = ww.add_bouton("Enregistrer",x,y, 100,30) btcree = ww.add_bouton(u"Créer",x+100,y, 100,30) btsupprime = ww.add_bouton(u"Supprimer",x+200,y, 100,30) btquit= ww.add_bouton("Abandonner",x+300,y, 100,30) ww.graindesel(btenregistre,fboutonenregistre, btcree,fboutoncree, btsupprime,fboutonsupprime, btquit,ww.ferme) ww.graindesel(9101,fboutonenregistre, 9102,fboutoncree, 9103,fboutonsupprime, 9109,ww.ferme) ww.define(auto=None) if valarrivee == -2: idch[0].focus() else: for i in range(nbch): idch[i].contenu(valarrivee[i]) idch[1].focus() ww.run() def forcehtm(): html=''' ''' open(os.path.dirname(__file__)+'\\the.htm',"w").write(html) def clipboardtxt(chaine=None): """ Extrait de Ponx """ global chaineretour import win32clipboard,win32con try: win32clipboard.OpenClipboard() if chaine is None: try: chaine=win32clipboard.GetClipboardData(win32con.CF_TEXT) #win32clipboard.EmptyClipboard() #win32clipboard.SetClipboardText(chaine) chaineretour=chaine return(chaine) except: chaineretour='' return('') else: try: win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(chaine) except: pass except: pass try: win32clipboard.CloseClipboard() except: pass # http://code.activestate.com/recipes/474121/ (r1) # HtmlClipboard # An interface to the "HTML Format" clipboard data format # #__author__ = "Phillip Piper (jppx1[at]bigfoot.com)" #__date__ = "2006-02-21" #__version__ = "0.1" import re import win32clipboard #--------------------------------------------------------------------------- # Convenience functions to do the most common operation def HasHtml(): """ Return True if there is a Html fragment in the clipboard.. """ cb = HtmlClipboard() return cb.HasHtmlFormat() def GetHtml(): """ Return the Html fragment from the clipboard or None if there is no Html in the clipboard. """ cb = HtmlClipboard() if cb.HasHtmlFormat(): return cb.GetFragment() else: return None def PutHtml(fragment): """ Put the given fragment into the clipboard. Convenience function to do the most common operation """ cb = HtmlClipboard() cb.PutFragment(fragment) #--------------------------------------------------------------------------- class HtmlClipboard: CF_HTML = None MARKER_BLOCK_OUTPUT = """Version:1.0\r\n StartHTML:%09d EndHTML:%09d StartFragment:%09d EndFragment:%09d StartSelection:%09d EndSelection:%09d SourceURL:%s""" MARKER_BLOCK_EX = """Version:(\S+)\s StartHTML:(\d+)\s EndHTML:(\d+)\s StartFragment:(\d+)\s EndFragment:(\d+)\s StartSelection:(\d+)\s EndSelection:(\d+)\s SourceURL:(\S+)""" MARKER_BLOCK_EX_RE = re.compile(MARKER_BLOCK_EX) MARKER_BLOCK = """Version:(\S+)\s StartHTML:(\d+)\s EndHTML:(\d+)\s StartFragment:(\d+)\s EndFragment:(\d+)\s SourceURL:(\S+)""" MARKER_BLOCK_RE = re.compile(MARKER_BLOCK) DEFAULT_HTML_BODY = "%s" def __init__(self): self.html = None self.fragment = None self.selection = None self.source = None self.htmlClipboardVersion = None def GetCfHtml(self): """ Return the FORMATID of the HTML format """ if self.CF_HTML is None: self.CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format") return self.CF_HTML def GetAvailableFormats(self): """ Return a possibly empty list of formats available on the clipboard """ formats = [] try: win32clipboard.OpenClipboard(0) cf = win32clipboard.EnumClipboardFormats(0) while (cf != 0): formats.append(cf) cf = win32clipboard.EnumClipboardFormats(cf) finally: win32clipboard.CloseClipboard() return formats def HasHtmlFormat(self): """ Return a boolean indicating if the clipboard has data in HTML format """ return (self.GetCfHtml() in self.GetAvailableFormats()) def GetFromClipboard(self): """ Read and decode the HTML from the clipboard """ try: win32clipboard.OpenClipboard(0) src = win32clipboard.GetClipboardData(self.GetCfHtml()) #print src self.DecodeClipboardSource(src) finally: win32clipboard.CloseClipboard() def DecodeClipboardSource(self, src): """ Decode the given string to figure out the details of the HTML that's on the string """ # Try the extended format first (which has an explicit selection) matches = self.MARKER_BLOCK_EX_RE.match(src) if matches: self.prefix = matches.group(0) self.htmlClipboardVersion = matches.group(1) self.html = src[int(matches.group(2)):int(matches.group(3))] self.fragment = src[int(matches.group(4)):int(matches.group(5))] self.selection = src[int(matches.group(6)):int(matches.group(7))] self.source = matches.group(8) else: # Failing that, try the version without a selection matches = self.MARKER_BLOCK_RE.match(src) if matches: self.prefix = matches.group(0) self.htmlClipboardVersion = matches.group(1) self.html = src[int(matches.group(2)):int(matches.group(3))] self.fragment = src[int(matches.group(4)):int(matches.group(5))] self.source = matches.group(6) self.selection = self.fragment def GetHtml(self, refresh=False): """ Return the entire Html document """ if not self.html or refresh: self.GetFromClipboard() return self.html def GetFragment(self, refresh=False): """ Return the Html fragment. A fragment is well-formated HTML enclosing the selected text """ if not self.fragment or refresh: self.GetFromClipboard() return self.fragment def GetSelection(self, refresh=False): """ Return the part of the HTML that was selected. It might not be well-formed. """ if not self.selection or refresh: self.GetFromClipboard() return self.selection def GetSource(self, refresh=False): """ Return the URL of the source of this HTML """ if not self.selection or refresh: self.GetFromClipboard() return self.source def PutFragment(self, fragment, selection=None, html=None, source=None): """ Put the given well-formed fragment of Html into the clipboard. selection, if given, must be a literal string within fragment. html, if given, must be a well-formed Html document that textually contains fragment and its required markers. """ if selection is None: selection = fragment if html is None: html = self.DEFAULT_HTML_BODY % fragment if source is None: source = "file://HtmlClipboard.py" fragmentStart = html.index(fragment) fragmentEnd = fragmentStart + len(fragment) selectionStart = html.index(selection) selectionEnd = selectionStart + len(selection) self.PutToClipboard(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source) def PutToClipboard(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source="None"): """ Replace the Clipboard contents with the given html information. """ try: win32clipboard.OpenClipboard(0) win32clipboard.EmptyClipboard() src = self.EncodeClipboardSource(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source) #print 284,src win32clipboard.SetClipboardData(self.GetCfHtml(), src) finally: win32clipboard.CloseClipboard() def EncodeClipboardSource(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source): """ Join all our bits of information into a string formatted as per the HTML format specs. """ # How long is the prefix going to be? dummyPrefix = self.MARKER_BLOCK_OUTPUT % (0, 0, 0, 0, 0, 0, source) lenPrefix = len(dummyPrefix) prefix = self.MARKER_BLOCK_OUTPUT % (lenPrefix, len(html)+lenPrefix, fragmentStart+lenPrefix, fragmentEnd+lenPrefix, selectionStart+lenPrefix, selectionEnd+lenPrefix, source) return (prefix + html) def DumpHtml(): cb = HtmlClipboard() print "GetAvailableFormats()=%s" % str(cb.GetAvailableFormats()) print "HasHtmlFormat()=%s" % str(cb.HasHtmlFormat()) if cb.HasHtmlFormat(): cb.GetFromClipboard() print "prefix=>>>%s<<>>%s<<>>%s<<>>%s<<>>%s<<>>%s<<1: if len(lvid.ldata)>=14: w.lvgoitem(lvid,len(lvid.ldata)-0) #w.lvscroll(lvid,(len(lvid.ldata)-15)*36) else: w.lvgoitem(lvid,len(lvid.ldata)-1) win32gui.PumpWaitingMessages() return ligsuivante def inputbox(titre="Saisir une valeur", texte="Saisir ici :", valeurinit=''): global wtop,wtopctrl try: bufwtop,bufwtopctrl=wtop,wtopctrl except: pass ww=win(titre, wclass="inputbox") ww.setprop(x=-1,y=-1,l=300,h=150) champ=ww.add_edit(100,20,180) ww.add_label(texte,10,21) ww.createmenu(contextmenu=u""" 9001 Quitter le menu 9002 Valider 9003 Abandonner DEFAULT:9002 """) #ww.graindesel(_9002=ww.valide) #ww.graindesel(_9003=ww.abandon) ww.graindeselkey(VK_RETURN=ww.valide) ww.graindeselkey(VK_ESCAPE=ww.abandon) ww.define(auto="OKCANCEL") wtop=ww wtopctrl=champ ret=ctypes.windll.user32.BringWindowToTop(ww.hwnd) champ.contenu(valeurinit) ww.ctrlfocus(champ) ww.ctrlselection(champ, debut=0, fin=255) ww.run() try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None pass if ww.fin=="VALIDE": return ww.result[2001][0] def inputbox2(titre="Saisir une valeur", texte="Saisir ici :", valeurinit='', texte2="Saisir ici :", valeurinit2=''): global wtop,wtopctrl try: bufwtop,bufwtopctrl=wtop,wtopctrl except: pass ww=win(titre, wclass="inputbox") ww.setprop(x=-1,y=-1,l=340,h=250) champ=ww.add_edit(140,40,180) ww.add_label(texte,10,21) champ2=ww.add_edit(140,80,180) ww.add_label(texte2,10,121) ww.createmenu(contextmenu=u""" 9001 Quitter le menu 9002 Valider 9003 Abandonner DEFAULT:9002 """) #ww.graindesel(_9002=ww.valide) #ww.graindesel(_9003=ww.abandon) ww.graindeselkey(VK_RETURN=ww.valide) ww.graindeselkey(VK_ESCAPE=ww.abandon) ww.define(auto="OKCANCEL") wtop=ww wtopctrl=champ ret=ctypes.windll.user32.BringWindowToTop(ww.hwnd) champ.contenu(valeurinit) champ2.contenu(valeurinit2) ww.ctrlfocus(champ) ww.ctrlselection(champ, debut=0, fin=255) ww.run() try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None pass if ww.fin=="VALIDE": return ww.result[2001][0],ww.result[2002][0] def inputbox3(titre="Saisir une valeur", texte="Saisir ici :", valeurinit='', texte2="Saisir ici :", valeurinit2='', texte3="Saisir ici :", valeurinit3=''): global wtop,wtopctrl try: bufwtop,bufwtopctrl=wtop,wtopctrl except: pass ww=win(titre, wclass="inputbox") ww.setprop(x=-1,y=-1,l=340,h=250) champ=ww.add_edit(140,20,180) ww.add_label(texte,10,21) champ2=ww.add_edit(140,70,180) ww.add_label(texte2,10,71) champ3=ww.add_edit(140,120,180) ww.add_label(texte3,10,121) ww.createmenu(contextmenu=u""" 9001 Quitter le menu 9002 Valider 9003 Abandonner DEFAULT:9002 """) #ww.graindeselkey(VK_RETURN=ww.valide) ww.graindeselkey(VK_ESCAPE=ww.abandon) ww.define(auto="OKCANCEL") wtop=ww wtopctrl=champ ret=ctypes.windll.user32.BringWindowToTop(ww.hwnd) champ.contenu(valeurinit) champ2.contenu(valeurinit2) champ3.contenu(valeurinit3) ww.ctrlfocus(champ) ww.ctrlselection(champ, debut=0, fin=255) ww.run() try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None pass if ww.fin=="VALIDE": return ww.result[2001][0],ww.result[2002][0],ww.result[2003][0] def pouinonechap(titre="Titre", texte="Texte", duree=0, image=None): global wtop,wtopctrl try: bufwtop,bufwtopctrl=wtop,wtopctrl except: pass def poui(self, id, event, *suite): self.fin="OUI" self.ferme() def pnon(self, id, event, *suite): self.fin="NON" self.ferme() def pabandon(self, id, event, *suite): self.fin="ABANDON" self.ferme() ww=win(titre, wclass="inputbox") ww.fond=(222,232,242) ww.setprop(x=-1,y=-1,l=377,h=180) ww.add_font("TXTLABEL","Arial narrow", 22, gras=True) if texte.find("\n"): multil=True yy=15 else: multil=False yy=25 ww.add_text(texte,x=10,y=yy,l=360,h=80, multiligne=multil, font="TXTLABEL", textcolor=(64,64,128)) btoui = ww.add_bouton(u"OUI {Entrée}", 1, 112, 120,30,poui) btnon = ww.add_bouton(u"NON {N}", 121, 112, 120,30,poui) btabandon = ww.add_bouton(u"Abandon {Echap}", 241, 112, 120,30,poui) ww.createmenu(contextmenu=u""" 9001 Quitter le menu 9002 OUI 9003 NON 9004 Abandon DEFAULT:9002 """) """ ww.graindesel(9002,poui) ww.graindesel(9003,pnon) ww.graindesel(9004,pabandon) """ ww.graindeselkey(VK_RETURN=poui) ww.graindeselkey(N=pnon) ww.graindeselkey(VK_ESCAPE=pabandon) ww.define(auto="NON") for i in range(10): time.sleep(0.05) win32gui.PumpWaitingMessages() ww.run() try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None pass return ww.fin def alert(txt1="Titre",txt2="",icon=0): global wtop,wtopctrl bufwtop,bufwtopctrl=wtop,wtopctrl wtop=0 wtopctrl=None if txt2=="": try: t1=txt1 except: t1=u"Problème dans le texte" if t1 is None: t1="-texte vide (None)-" vret=win32ui.MessageBox(t1,"",icon) else: try: t1=txt1 except: t1=u"Problème dans le titre" try: t2=txt2 except: t2=u"Problème dans le texte" if t1 is None: t1="-titre vide (None)-" if t2 is None: t2="-texte vide (None)-" if isinstance(t2,list): t2=repr(t2) vret=win32ui.MessageBox(t2,t1,icon) try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None def messagebox(texte="",title="Titre",icon=1): alert(title,texte,icon) def popup(text="XXX", nbsec=5, title="Titre", typ=0): """Typ: 0 OK button. 1 OK and Cancel buttons. 2 Abort, Retry, and Ignore buttons. 3 Yes, No, and Cancel buttons. 4 Yes and No buttons. 5 Retry and Cancel buttons. au retour : 6 OUI 7 NON """ global wtop,wtopctrl bufwtop,bufwtopctrl=wtop,wtopctrl wtop=0 wtopctrl=None wsh = win32com.client.Dispatch("WScript.Shell") vret=wsh.Popup(text, nbsec, title, typ) try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None return vret def popupthreaded(text="XXX", nbsec=5, title="Titre", typ=0): """ Comme popup, mais en un thread (rend la main immédiatement) """ global wtop,wtopctrl bufwtop,bufwtopctrl=wtop,wtopctrl wtop=0 wtopctrl=None import threading,win32com.client wsh = win32com.client.Dispatch("WScript.Shell") def tacheu(): wsh.Popup(text, nbsec, title, typ) tach=threading.Thread(target=tacheu,name="popupthreaded") tach.setDaemon(True) tach.start() def choixcouleur(): w=win("",0,0,860+2,160+30+30+2) w.setprop(CAPTION=False, SYSMENU=False, MINIMIZEBOX=False, MAXIMIZEBOX=False, THICKFRAME=False, POPUP=True) choixcouleur.couleur=(-1,-1,-1) def suiviclic(w,x,y,*suite): c=int((x-0)/24) l=int((y-0)/32) #print "Ligne, Col : ",l,c dc = win32gui.GetWindowDC(w.hwnd) color=win32gui.GetPixel(dc,x,y) b=int(color/256/256) color=color-b*256*256 v=int(color/256) r=color-v*256 #print "R V B: ",r,v,b choixcouleur.couleur=(r,v,b) w.ferme() l=0 c=-1 nb=0 for r in (0,51,102,153,204,255): for v in (0,51,102,153,204,255): for b in (0,51,102,153,204,255): c+=1 nb+=1 if c>35: l+=1 c=0 st="""color 0 0 0 pen 5 0 brush """+str(r)+" "+str(v)+" "+str(b)+""" rectangle """+str(c*24)+" "+str(l*32)+" "+str(c*24+25)+" "+str(l*32+33) w.add_dessin(st) btclose=w.add_bouton(texte="Abandonner" , x=2,y=160+30+2, l=860-1,h=30, fonction=w.ferme) w.graindesel("CLICK",suiviclic) w.define(auto="NO") w.run() return choixcouleur.couleur def fichierchoix(dirinitial=os.getcwd(),preselection="",filtre="*.*", titre='Choisir un ou des fichier(s)', explorer="OUI",choixmultiple="OUI"): """ retourne une liste contenant : - le dossier, - la liste des fichiers sélectionnés Exemple : [u'D:\\mondir','u'Fichier1.txt','u'Fichier2.txt','u'Fichier3.txt'] Si abandon : ['',''] Si un seul fichier : [u'D:\\monDir','u'monFichier.txt'] voir aussi: GetSaveFileNameW liste des flags possibles: OFN_ALLOWMULTISELECT &H200 Autoriser la sélection multiple de fichiers. OFN_CREATEPROMPT &H2000 Afficher une fenêtre de confirmation de création de fichier. OFN_EXPLORER &H80000 Donne un style 'Explorer' à la boîte de dialogue (par défaut). OFN_EXTENSIONDIFFERENT &H400 Indique que l'utilisateur a choisi une extension différente de celle par défaut. OFN_FILEMUSTEXIST &H1000 Seuls des fichiers existants peuvent être saisis. OFN_HIDEREADONLY &H4 Case à cocher 'Lecture seule' invisible. OFN_LONGNAMES &H200000 Gestion des noms longs pour les boîtes de dialogue n'ayant pas le style 'Explorer'. OFN_NOCHANGEDIR &H8 Conserve le répertoire d'origine à la fermeture de la fenêtre. OFN_NODEREFERENCELINKS &H100000 La boîte de dialogue prendra le nom et le chemin du raccourci sélectionné. OFN_NOLONGNAMES &H40000 Utilise les noms courts de fichier (sans effet dans le cas des fenêtres du type 'Explorer'). OFN_NONETWORKBUTTON &H20000 Cache (désactive) le bouton 'Réseau'. OFN_NOREADONLYRETURN &H8000 Ne sélectionne pas la case à cocher 'Lecture seule'. OFN_NOTESTFILECREATE &H10000 Le fichier ne sera pas créé avant la fermeture de la fenêtre. OFN_NOVALIDATE &H100 Ne vérifie pas la validité de la saisie (validité du nom de fichier). OFN_OVERWRITEPROMPT &H2 Afficher un message de confirmation d'écrasement de fichier si celui-ci existe déjà. OFN_PATHMUSTEXIST &H800 Les chemins et fichiers saisis doivent exister. OFN_READONLY &H1 La case 'Lecture seule' est cochée à la création de la fenêtre. OFN_SHAREAWARE &H4000 Ignorer les erreurs de partage réseau. OFN_SHOWHELP &H10 Afficher le bouton 'Aide' dans la boîte de dialogue. """ flag = win32con.OFN_SHAREAWARE | win32con.OFN_HIDEREADONLY if explorer=="OUI": flag |= win32con.OFN_EXPLORER if choixmultiple=="OUI": flag |= win32con.OFN_ALLOWMULTISELECT """ # GetSaveFileNameW # GetOpenFileNameW try: fname, customfilter, flags=win32gui.GetOpenFileNameW( InitialDir=dirinitial, #dossier ouvert par défaut Flags=flag, File=preselection, #nom de fichier proposé à l'ouverture DefExt='', #extension par défaut (pas utilisé ?) ; ex.: 'pyw' Title=titre, Filter=filtre, CustomFilter="*.*", #filtre initial pour l'affichage des fichiers (si non explorer='OUI' ) FilterIndex=1) #filtre sélectionné à l'ouverture ; position pré-sélectionnée dans la liste des filtres possibles """ try: vret=win32gui.GetOpenFileNameW(Title=titre, File=preselection, Filter=filtre, InitialDir=dirinitial, Flags=flag) #vret=win32gui.GetOpenFileNameW(Title='Choisir une image', File='', Filter='JPG\0*.jpg\0', InitialDir=u"D:\\dev\\ponxite\\test\\fichiers", Flags=flag) except: vret="" lf=[""] if vret!="": lf=vret[0].split(chr(0)) if len(lf)==1: lf=os.path.split(lf[0]) return lf def choixdir(dirinitial="C:\\"): import win32com.shell.shell,win32com.shell.shellcon """ flags = shellcon.BIF_STATUSTEXT shell.SHBrowseForFolder(0, # parent HWND None, # root PIDL. "Choisir un Dossier ", # title flags, # flags BrowseCallbackProc, # callback function dirinitial # 'data' param for the callback ) """ # 2e version : impossible de remonter if dirinitial is None: pidl=None else: desktop = win32com.shell.shell.SHGetDesktopFolder() cb, pidl, extra = desktop.ParseDisplayName(0, None, dirinitial) r1,r2,r3 = win32com.shell.shell.SHBrowseForFolder(0, # parent HWND pidl, # root PIDL. "Choisir un Dossier ", # title 0, None, None ) if r1 is None: return None else: return win32com.shell.shell.SHGetPathFromIDList(r1) def choixfichier(ppath=None,patterns='py', titre='Choisir un fichier'): """ exemple: fichier=pywig.choixfichier(vglob.dircourant, 'Python (.py .pyw)\0*.py;*.pyw\0Txt (.txt)\0*.txt\0Tous (*.*)\0*.*\0') si pas de choix, retourne "" """ if ppath is None: ppath=os.getcwd() result=fichierchoix(dirinitial=ppath,preselection="",filtre=patterns, titre=titre, explorer="OUI",choixmultiple="NON") if result[0]=="": r="" else: r=os.path.join(result[0],result[1]) return r def choixfichiervlist(ppath=None,patterns='py'): def recupytime(pt): return datetime.datetime(year=pt.year,month=pt.month,day=pt.day,hour=pt.hour,minute=pt.minute,second=pt.second) def lfdir(dircourant, patterns='py'): ''' 1 date création 2 date dernier accès (si NtfsDisable LastAccessUpdate est à 0) 3 date dernière modif 5 taille 8 Nom ''' patt='(' for i in patterns.split(','): patt += i+'|' patt = patt[:-1]+')$' #print patt rpatt=re.compile(patt, re.IGNORECASE) try: items=win32file.FindFilesW(dircourant + "\\*") lret=[[item[8],recupytime(item[3]),recupytime(item[1]),item[5]] for item in items if rpatt.search(item[8])] return lret except win32file.error, details: raise return if ppath=="" or (ppath is None): dircourant=os.getcwd() else: dircourant=ppath r=lfdir(dircourant,patterns) #print dt.year,dt.month,dt.day,' ',dt.hour,dt.minute,dt.second #print str(dt) w=win(u"Choix Fichier") w.x=-1 w.y=-1 w.l=636 w.h=568 w.fond=(220,220,240) t="xx janvier février mars avril mai juin juillet août septembre octobre novembre décembre" nmois=t.split() def doubleclic(w, lig,col, *suite): w.fin=choixfichier.ldisc[lig][0] w.ferme() def titreclic(w, col,bof, *suite): def rcol(l): return l[col] if w.colonnetri==col: globaldisc.reverse() else: globaldisc.sort(key=rcol) w.colonnetri=col champselection.contenu('') choixfichier.ldisc=globaldisc[:] w.replacelliste(odisc, choixfichier.ldisc) def controldraw(w, lig,col, *suite): font=None colorback=None colortext=None if col==1: try: if choixfichier.ldisc[lig][6]>0: colorback=w.color(255,255,192) except: pass return font,colorback,colortext def valider(w,el,typevent,*suite): lig=w.ligcourante if lig is None: w.fin=champselection.contenu() else: w.fin=choixfichier.ldisc[lig][0] w.ferme() def suitdown(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: w.ctrlfocus(odisc) w.lvgoitem(odisc,0-1) # -1 car le {DOWN} n'est pas intercepté def suitend(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: w.ctrlfocus(odisc) w.lvgoitem(odisc,len(odisc.ldata)-1) def ftab(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: pass else: w.ligcourante=None w.ctrlfocus(champselection) time.sleep(0.250) def aide(w,el,typevent,*suite): w.alert("pas besoin d'aide, c'est trop simple...") def suiviselection(w,el,typevent,*suite): cfocus=w.getfocus() if cfocus==champselection: crit=str(w.gettext(el)) crit=crit.replace('\t','') crit=crit.replace(chr(0),'') crit=crit.replace('\r','') crit=crit.replace('\n','') crit=crit.rstrip() w.fin=None if len(crit)>1 : recritere=re.compile(crit,re.IGNORECASE) choixfichier.ldisc=[i for i in globaldisc if recritere.search(i[0])] w.replacelliste(odisc, choixfichier.ldisc) globaldisc=r choixfichier.ldisc=globaldisc[:] t_largeur=[ 280, 120, 120, 80] t_align = [ 'LEFT', 'CENTER', 'CENTER', 'RIGHT'] t_titre = [ "Nom", "Modif", u"Création", "Taille"] t_format= [ 0, 15, 15, 21] odisc = w.add_vlist(0,30+25, 600+20,475, t_largeur, t_align, t_titre, choixfichier.ldisc, False, True, False, None, 0, t_format) w.add_label(u"Fichier",5,5,55,20) champselection = w.add_edit(60,5,300,20, False) w.add_text(texte=u"Dossier: "+unicode(dircourant,'utf-8','ignore'),x=5,y=30,l=600,h=20, multiligne=False, font="DEFAULT", textcolor=(128,0,0)) w.createmenu(contextmenu=u""" 9290 rien (fermer le menu) 9291 &Valider 9292 Aide 9299 &Quitter ou Abandonner """) w.graindesel(9291,valider, 9299,w.ferme, 9292,aide, champselection,suiviselection) try: w.graindesel(str(odisc.id)+"CDRAW",controldraw) w.graindesel(str(odisc.id)+"LDOUBLECLICK",doubleclic) w.graindesel(str(odisc.id)+"TITRECLICK",titreclic) except: pass w.graindeselkey( VK_RETURN=valider, VK_TAB=ftab, VK_DOWN=suitdown, VK_NEXT=suitdown, VK_END=suitend) w.define(auto=None) if odisc is not None: w.visulliste(odisc) w.ctrlfocus(champselection) w.colonnetri=999 w.fin=None w.run() if w.fin is None: vret=champselection.contenu() #,False) else: if w.ligcourante is None: vret=w.fin #,False) else: vret=w.fin #,True) del w return vret def filechoice(types=".htm;*.html", descriptif="fichiers HTML/HTA|*.htm;*.html;*.hta|Tous les fichiers|*.*||", startdirfile=os.getcwd(), title="Choisissez un fichier"): global wtop,wtopctrl bufwtop,bufwtopctrl=wtop,wtopctrl wtop=0 wtopctrl=None # win32con.OFN_FILEMUSTEXIST | win32con.OFN_EXPLORER | win32con.OFN_ALLOWMULTISELECT | win32con.OFN_HIDEREADONLY o = win32ui.CreateFileDialog( 1, types, startdirfile, win32con.OFN_EXPLORER, descriptif, None) ###o = win32ui.CreateFileDialog( 1, ".htm;*.html", "", win32con.OFN_HIDEREADONLY, "fichiers HTML/HTA|*.htm;*.html;*.hta|Tous les fichiers|*.*||", None) #o.SetOFNInitialDir(r'C:\\Dev') o.SetOFNTitle('Choisissez un fichier') if o.DoModal() == win32con.IDOK: vret=(o.GetPathName(),o.GetFileName()) else: #messagebox(u"Vous n'avez pas choisi de fichier !","",0) popup(u"Vous n'avez pas choisi de fichier !",1,"Quoi ?") vret=(None, None) try: wtop,wtopctrl=bufwtop,bufwtopctrl except: wtop,wtopctrl=None,None return vret class wsh(object): def __init__(self): self.shell = win32com.client.Dispatch('Shell.Application') self.wshell = win32com.client.Dispatch("WScript.Shell") def popup(self,text="XXX", nbsec=5, title="Titre", typ=0): """Typ: 0 OK button. 1 OK and Cancel buttons. 2 Abort, Retry, and Ignore buttons. 3 Yes, No, and Cancel buttons. 4 Yes and No buttons. 5 Retry and Cancel buttons. """ self.wshell.Popup(text, nbsec, title, typ) def shellzip(self,fichierzip,dossiersource): """ Attention, il faut attendre le temps nécessaire, avant de fermer le script. """ open(fichierzip,"wb").write(chr(0x50)+chr(0x4B)+chr(0x05)+chr(0x06)+chr(0)*18) self.shell.NameSpace(fichierzip).copyhere(dossiersource,0x00 + 0x10 + 0x100) """ for ofile in self.shell.NameSpace(dossiersource).items(): print ofile self.shell.NameSpace(fichierzip).copyhere(ofile) time.sleep(0.5016) """ def shellunzip(self,fichierzip,dossierdestination): for ofile in self.shell.NameSpace(fichierzip).items(): #print ofile self.shell.NameSpace(dossierdestination).copyhere(ofile) def shellinfozip(self,fichierzip): for oFile in self.shell.NameSpace(fichierzip).items(): pass print oFile.Name, print oFile.Type, print oFile.ModifyDate, print oFile.IsFileSystem, print oFile.IsFolder, print oFile.Path, print oFile.Size def test(self): """ BrowseForFolder Creates a dialog box that enables the user to select a folder and then returns the selected folder's Folder object. CascadeWindows Cascades all of the windows on the desktop. This method has the same effect as right-clicking the taskbar and selecting Cascade Windows. ControlPanelItem Runs the specified Control Panel (*.cpl) application. If the application is already open, it will activate the running instance. EjectPC Ejects the computer from its docking station. This is the same as clicking the Start menu and selecting Eject PC, if your computer supports this command. Explore Opens a specified folder in a Windows Explorer window. FileRun Displays the Run dialog to the user. This method has the same effect as clicking the Start menu and selecting Run. FindComputer Displays the Search Results: Computers dialog box. The dialog box shows the result of the search for a specified computer. FindFiles Displays the Find: All Files dialog box. This is the same as clicking the Start menu and then selecting Search (or its equivalent under systems earlier than Windows XP. Help Displays the Windows Help and Support Center. This method has the same effect as clicking the Start menu and selecting Help and Support. MinimizeAll Minimizes all of the windows on the desktop. This method has the same effect as right-clicking the taskbar and selecting Minimize All Windows on older systems or clicking the Show Desktop icon in the Quick Launch area of the taskbar in Windows 2000 or Windows XP. NameSpace Creates and returns a Folder object for the specified folder. Open Opens the specified folder. RefreshMenu Refreshes the contents of the Start menu. Used only with systems preceding Windows XP. SetTime Displays the Date and Time Properties dialog box. This method has the same effect as right-clicking the clock in the taskbar status area and selecting Adjust Date/Time. ShutdownWindows Displays the Shut Down Windows dialog box. This is the same as clicking the Start menu and selecting Shut Down. Suspend Not implemented. TileHorizontally Tiles all of the windows on the desktop horizontally. This method has the same effect as right-clicking the taskbar and selecting Tile Windows Horizontally. TileVertically Tiles all of the windows on the desktop vertically. This method has the same effect as right-clicking the taskbar and selecting Tile Windows Vertically. TrayProperties Displays the Taskbar and Start Menu Properties dialog box. This method has the same effect as right-clicking the taskbar and selecting Properties. UndoMinimizeALL Restores all desktop windows to the same state they were in before the last MinimizeAll command. This method has the same effect as right-clicking the taskbar and selecting Undo Minimize All Windows on older systems or a second clicking of the Show Desktop icon in the Quick Launch area of the taskbar in Windows 2000 or Windows XP. Windows Creates and returns a ShellWindows object. This object represents a collection of all of the open windows that belong to the Shell. """ self.shell.ControlPanelItem("INETCPL.cpl") #Propriétés internet self.shell.BrowseForFolder(0, "DEV - batch", 0, "C:\\Dev\\bat") #choix dossier #self.shell.FileRun() def explorerinvoke(self, chemin,fichier="",verbe=""): """ invoque une ligne du menu contextuel de l'explorateur. paramètres: - chemin (peut être un disque) - fichier (facultatif, si "", alors on traite le dossier) - verbe, la ligne du menu à invoquer Notes: Le script ne doit pas être fermé tant que la fonction appelée n'est pas terminée. Exemples: explorerinvoke("L:","",u"Propriétés") explorerinvoke("L:\\","choixdir.py",u"Textpad") explorerinvoke("L:\\","choixdir.py",u"Créer un raccourci") (cet exemple travaille de manière invisible) """ if verbe=="": return #self.shell #= win32com.client.Dispatch('Shell.Application') #self.wshell #=win32com.client.Dispatch("WScript.Shell") objFolder = self.shell.Namespace(chemin) if fichier!="": objFolderItem = objFolder.ParseName(fichier) else: objFolderItem = objFolder.Self colVerbs = objFolderItem.Verbs() ordre=None verbe=verbe.upper() num=-1 for objVerb in colVerbs: num+=1 if objVerb.Name!="": st=objVerb.Name st=st.replace('&','') st=st.upper() #print num,' \t ',st,' ',verbe, if st==verbe: ordre=objVerb #objVerb.DoIt() colVerbs.Item(num).DoIt() n=wshell.Popup(verbe,1,u"Commande envoyée",0) break class IEpilot(object): def __init__(self, url=None, visible=1, **args): args.setdefault('instanceurl',None) args.setdefault('attendurl',None) args.setdefault('x',200) args.setdefault('y',100) args.setdefault('width',400) args.setdefault('height',300) args.setdefault('ToolBar',False) args.setdefault('AddressBar',False) args.setdefault('MenuBar',False) args.setdefault('StatusBar',True) for k,v in args.items(): setattr(self,k,v) self.doc='' self.links=[] self.link={} self.forms=[] self.form={} self.nbforms=0 self.felems=[] self.fields=[] self.fieldTyp={} self.fieldVposs={} self.field={} self.buttons=[] self.button={} self.scripts=[] self.script={} self.flagnew=True self.ie=None self.attendurl = self.attendurl.lower() if self.attendurl is not None: nbs=12*10 flagcontinue=True clsid= '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hie=win32com.client.Dispatch(clsid) time.sleep(0.05) while flagcontinue and nbs>0: #print 7064,len(hie),hie for instance in hie: #print 5891,instance.LocationURL, self.attendurl, (instance.LocationURL.find(self.attendurl)) #import ponx #ponx.msginfo("4150",str(instance.LocationURL)+" a: "+self.attendurl) ###if instance.LocationURL==self.attendurl: #print 5895,len(hie),' i:',instance.LocationURL,' a:',self.attendurl location=instance.LocationURL.lower() if location.find(self.attendurl)>-1: self.ie=instance self.x=self.ie.Left self.y=self.ie.Top self.width=self.ie.Width self.height=self.ie.Height self.ToolBar=False self.AddressBar=False self.setdefault=MenuBar=False self.setdefault=StatusBar=False flagcontinue=False #print "Trouvé !!!!",252 break if flagcontinue: time.sleep(0.05) nbs-=1 self.navigUrlsuite() def navigUrl(self,url): """charge une page, d'après son URL """ url=url.replace('\\','/') self.ie.Navigate(url) self.document=self.ie.Document self.doc=self.ie.Document self.body=self.ie.Document.Body ###self.window=self.ie.Document.parentWindow #print 7589,url self.flagnew=True def navigUrlsuite(self): """comme navigUrl, mais après l'URL mise en place """ self.doc=self.ie.Document self.document=self.ie.Document self.body=self.ie.Document.Body self.flagnew=True #dd=time.time() ###self.window=self.ie.Document.parentWindow # (trop) long !!! ??? #df=time.time() #print 7113,df-dd #print 6092,repr(self.body.window) def trouvewindow(self): self.window=self.ie.Document.parentWindow # Attention, long ! #*** 19.11.06 v1.18 *** def calljscript(self,code): """appelle une fonction javascript """ self.ie.Navigate(' javascript:'+code) time.sleep(0.01) #*** 19.11.06 v1.18 *** def setScript(self,num='1',source=''): """affecte (met en place) un script ; attention, le script n'est pas évalué car l'évaluation se fait au chargement de la page. """ self.loadLists() #print'-'*55 #print self.script[num].innerHTML #print'-'*55 time.sleep(0.2) self.script[num].innerHTML='\n\n '+source time.sleep(0.2) self.loadLists() """ print'='*55 print source print'='*55 print num,type(num) print'-'*55 print self.script[num].innerHTML print'*'*55 """ def GetUrl(self): """retourne l'URL courante """ return self.ie.LocationURL def GetHtml(self): """retourne le code HTML de la page courante """ #return self.doc.body.outerHTML return self.ie.Document.body.outerHTML def setbodyhtml(self, html): """affecte le contenu de BODY """ self.doc.body.outerHTML=html def GetDocument(self): """retourne le code HTML de la page courante """ return self.ie.Document def visible(self, flag=True): """rend IE visible/invisible """ if flag==True: self.ie.Visible=1 else: self.ie.Visible=0 def alert(self, msg='Alerte'): """affiche un petit message """ self.window.alert(msg) def close(self): try: self.ie.Quit() except: pass self.ie=None def getDom(self): """Retourne, sous forme texte, le DOM, à partir du node courant. """ global tab,buffer class sout(object): def __init__(self): self.buf='' def pr(self,*txt): for i in txt: self.buf=self.buf+' '+i.encode('cp1252','replace') self.buf=self.buf+'\r\n' def prrc(self,*txt): for i in txt: self.buf=self.buf+i.encode('cp1252','replace')+'\r\n' def pt(self,*txt): for i in txt: self.buf=self.buf+i.encode('cp1252','replace')+' ' def raz(self): self.buf='' def sprint(self): print self.buf tab='' buffer=sout() def lchild(docpos): global tab,buffer def pri(*txt): buffer.pr(*txt) def prt(*txt): buffer.pt(*txt) tab+=' ' if docpos.nodeType==3: pri(tab,"-->", docpos.nodename, docpos.nodeValue) else: prt(tab) #docpos.nodename, if str(docpos.nodeValue)!="None": prt(docpos.nodeValue) #print docpos.nodeType, if docpos.nodeType==1: prt(docpos.tagName) try: if docpos.type!='': prt(' TYPE=',docpos.type) except: pass if docpos.id!='': prt(' ID=',docpos.id) try: if docpos.name!='': prt(' NOM=',docpos.name) except: pass try: if docpos.value!='': pri('VALUE=',docpos.value) else: pri('') except: pri('') elif docpos.nodeType==222: pri(docpos.tagName,'*'*33) else: pri('') nb=0 for item in docpos.childNodes: lchild(item) tab=tab[:-4] lchild(self.doc) return buffer.buf def connectid(self,id): return self.doc.getElementById(id) def refresh(self): """recharge la page """ self.ie.Refresh() def addressbar(self,flag=False): #print self.ie.AddressBar self.ie.AddressBar=flag def menubar(self,flag=False): #print self.ie.MenuBar self.ie.MenuBar=flag def statusbar(self,flag=False): #print self.ie.StatusBar self.ie.StatusBar=flag def toolsbar(self,flag=False): #print self.ie.ToolBar self.ie.ToolBar=flag def title(self,valeur=None): if valeur: self.doc.title=valeur pass else: return self.doc.title """ HotKeys exemple d'utilisation : if __name__ == '__main__': #obligatoire à cause du multiProcessing lhk=( [0, 222, hhk_2], # touche ² [win32con.MOD_WIN, win32con.VK_F4, hhk_f4], # touche {windows}{F4} [win32con.MOD_CONTROL, ord(u"M"), hhk_cm], # touche {Ctrl}{M} [win32con.MOD_ALT+win32con.MOD_SHIFT, ord(u"B"), hhk_asn], # touche {Alt+Shift}{B} ) photk=Process(target=pywig.hotkey_wait, args=(lhk,)) photk.start() ..._suite_du_programme_ pywig.hotkey_unregister(3) photk.terminate() Les fonctions en callback étant : hhk_2 hhk_f4 hhk_cm hhk_asn Si une fonction callback retourne 999, cela ferme les hotkeys """ class hotkey_p(object): def __init__(self, *defhotkeys): self.func={} self.par={} self.defhotkeys=defhotkeys self.nb=len(defhotkeys) #for n,hk in enumerate(*self.defhotkeys): self.register() ''' for n,hk in enumerate(self.defhotkeys): self.func[n]=hk[2] if len(hk)>3: self.par[n]=hk[3] else: self.par[n]=None try: if not ctypes.windll.user32.RegisterHotKey(None, n, hk[0], hk[1]): print "Pb sur Hotkey",n except: pass ''' def register(self): for n,hk in enumerate(self.defhotkeys): self.func[n]=hk[2] if len(hk)>3: self.par[n]=hk[3] else: self.par[n]=None ctypes.windll.user32.RegisterHotKey(None, n, hk[0], hk[1]) try: if not ctypes.windll.user32.RegisterHotKey(None, n, hk[0], hk[1]): #print "Pb sur Hotkey",n pass except: pass def unregister(self): for n in range(len(self.defhotkeys)): try: ctypes.windll.user32.UnregisterHotKey(None, n) except: pass def termine(self): for n in range(len(self.defhotkeys)): try: ctypes.windll.user32.UnregisterHotKey(None, n) except: pass def wait(self): msg = ctypes.wintypes.MSG() while ctypes.windll.user32.GetMessageA( ctypes.byref(msg), None, 0, 0) != 0: if msg.message == win32con.WM_HOTKEY: # msg.wParam contient le numéro de la HotKey (ID) vret = self.func[msg.wParam](self.par[msg.wParam]) if vret == 999: ctypes.windll.user32.PostQuitMessage(0) break self.termine() def hotkey_unregister(nb): for n in range(nb): try: ctypes.windll.user32.UnregisterHotKey(None, n) except: pass def hotkey_init(*lhk): global pwg_hotkey pwg_hotkey=hotkey_p(*lhk) def hotkey_register(*lhk): global pwg_hotkey pwg_hotkey.register() def hotkey_wait(*lhk): global pwg_hotkey if pwg_hotkey is None: hotkey_init(*lhk) else: pwg_hotkey.register() msg = ctypes.wintypes.MSG() while ctypes.windll.user32.GetMessageA( ctypes.byref(msg), None, 0, 0) != 0: if msg.message == win32con.WM_HOTKEY: # msg.wParam contient le numéro de la HotKey (ID) vret = pwg_hotkey.func[msg.wParam](pwg_hotkey.par[msg.wParam]) if vret == 888: #ctypes.windll.user32.PostQuitMessage(0) ctypes.windll.user32.TranslateMessage(ctypes.byref(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg)) continue elif vret == 999: ctypes.windll.user32.PostQuitMessage(0) break time.sleep(0.01) pwg_hotkey.termine() def imp_pil(): global PIL,Image try: import PIL,PIL.Image,PIL.ImageWin import Image except: pass def imp_scintilla(): execfile("scintillacon.py",globals(),globals()) if __name__ == '__main__': pass