Python实现Windows上气泡提醒效果的方法
本文实例讲述了Python实现Windows上气泡提醒效果的方法。分享给大家供大家参考。具体实现方法如下:
#-*-encoding:gbk-*- importsys importos importstruct importtime importwin32con fromwin32apiimport* #TryanduseXPfeatures,sowegetalpha-blendingetc. try: fromwinxpguiimport* exceptImportError: fromwin32guiimport* classPyNOTIFYICONDATA: _struct_format=( "I"#DWORDcbSize;结构大小(字节) "I"#HWNDhWnd;处理消息的窗口的句柄 "I"#UINTuID;唯一的标识符 "I"#UINTuFlags; "I"#UINTuCallbackMessage;处理消息的窗口接收的消息 "I"#HICONhIcon;托盘图标句柄 "128s"#TCHARszTip[128];提示文本 "I"#DWORDdwState;托盘图标状态 "I"#DWORDdwStateMask;状态掩码 "256s"#TCHARszInfo[256];气泡提示文本 "I"#union{ #UINTuTimeout;气球提示消失时间(毫秒) #UINTuVersion;版本(0forV4,3forV5) #}DUMMYUNIONNAME; "64s"#TCHARszInfoTitle[64];气球提示标题 "I"#DWORDdwInfoFlags;气球提示图标 ) _struct=struct.Struct(_struct_format) hWnd=0 uID=0 uFlags=0 uCallbackMessage=0 hIcon=0 szTip='' dwState=0 dwStateMask=0 szInfo='' uTimeoutOrVersion=0 szInfoTitle='' dwInfoFlags=0 defpack(self): returnself._struct.pack( self._struct.size, self.hWnd, self.uID, self.uFlags, self.uCallbackMessage, self.hIcon, self.szTip, self.dwState, self.dwStateMask, self.szInfo, self.uTimeoutOrVersion, self.szInfoTitle, self.dwInfoFlags ) def__setattr__(self,name,value): #avoidwrongfieldnames ifnothasattr(self,name): raiseNameError,name self.__dict__[name]=value classMainWindow: def__init__(self,title,msg,duration=3): #RegistertheWindowclass. wc=WNDCLASS() hinst=wc.hInstance=GetModuleHandle(None) wc.lpszClassName="PythonTaskbarDemo" #字符串只要有值即可,下面3处也一样 wc.lpfnWndProc={win32con.WM_DESTROY:self.OnDestroy} #couldalsospecifyawndproc. classAtom=RegisterClass(wc) #CreatetheWindow. style=win32con.WS_OVERLAPPED|win32con.WS_SYSMENU self.hwnd=CreateWindow(classAtom,"TaskbarDemo",style, 0,0,win32con.CW_USEDEFAULT,win32con.CW_USEDEFAULT, 0,0,hinst,None ) UpdateWindow(self.hwnd) iconPathName=os.path.abspath(os.path.join(sys.prefix,"pyc.ico")) icon_flags=win32con.LR_LOADFROMFILE|win32con.LR_DEFAULTSIZE try: hicon=LoadImage(hinst,iconPathName,win32con.IMAGE_ICON,0,0,icon_flags) except: hicon=LoadIcon(0,win32con.IDI_APPLICATION) flags=NIF_ICON|NIF_MESSAGE|NIF_TIP nid=(self.hwnd,0,flags,win32con.WM_USER+20,hicon,"Balloontooltipdemo") Shell_NotifyIcon(NIM_ADD,nid) self.show_balloon(title,msg) time.sleep(duration) DestroyWindow(self.hwnd) defshow_balloon(self,title,msg): #ForthismessageIcan'tusethewin32guistructurebecause #itdoesn'tdeclarethenew,requiredfields nid=PyNOTIFYICONDATA() nid.hWnd=self.hwnd nid.uFlags=NIF_INFO #typeofballoonandtextarerandom nid.dwInfoFlags=NIIF_INFO nid.szInfo=msg[:64] nid.szInfoTitle=title[:256] #CalltheWindowsfunction,notthewrappedone fromctypesimportwindll Shell_NotifyIcon=windll.shell32.Shell_NotifyIconA Shell_NotifyIcon(NIM_MODIFY,nid.pack()) defOnDestroy(self,hwnd,msg,wparam,lparam): nid=(self.hwnd,0) Shell_NotifyIcon(NIM_DELETE,nid) PostQuitMessage(0)#Terminatetheapp. if__name__=='__main__': MainWindow("您有一条短消息","您该睡觉了")
希望本文所述对大家的Python程序设计有所帮助。