def __init__(self):
        iconEmbededN = 0
        numberOfFilesN = 0

        fileListN = self.dir_list(
            'C:\\Users\\tigerlyb\\Documents\\PE\\normal\\')

        for f in fileListN:
            numberOfFilesN = numberOfFilesN + 1
            print "File Number(NormalFile): ", numberOfFilesN
            print f
            if win32gui.ExtractIconEx(f, -1):
                print "Icon Embedded(NormalFile)."
                iconEmbededN = iconEmbededN + 1
                large, small = win32gui.ExtractIconEx(f, 0)
                print large[0], small[0]
                print win32gui.ExtractIconEx(f, 0)
                win32gui.DestroyIcon(small[0])
                self.pixmap = QtGui.QPixmap.fromWinHBITMAP(
                    self.bitmapFromHIcon(large[0]), 2)
                dest = "C:\\Users\\tigerlyb\\Documents\\PE\\iconN\\" + f[
                    42:len(f) - 4] + ".ico"
                self.pixmap.save(dest)
                print ""
            else:
                print "No Icon Embedded(NormalFile)."
                print ""

        print ""
        print "Total Number Of Files Embedded Icon(NormalFile): ", iconEmbededN
    def __init__(self):
        iconEmbededM = 0
        numberOfFilesM = 0
        
        fileListM = self.dir_list('E:\\Users\\tigerlyb\\Documents\\CSCI8260Project\\malware\\')
        
        for f in fileListM:
            if f != 'E:\\Users\\tigerlyb\\Documents\\CSCI8260Project\\malware\\.DS_Store':
                numberOfFilesM = numberOfFilesM + 1            
                print "File Number(Malware): ", numberOfFilesM
                print f
                if win32gui.ExtractIconEx(f, -1):
                    print "Icon Embedded(Malware)."
                    print ""
                    iconEmbededM = iconEmbededM + 1                  
                    large, small = win32gui.ExtractIconEx(f, 0)
                    print win32gui.ExtractIconEx(f, 0)

                    win32gui.DestroyIcon(small[0])                    
                    self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.bitmapFromHIcon(large[0]), 2)
                    dest = "C:\\Users\\tigerlyb\\Documents\\PE\\iconM\\" + f[52:len(f)-4] + ".ico"
                    self.pixmap.save(dest)
                else:
                    print "No Icon Embedded(Malware)."
                    print ""      
                
        print ""        
        print "Total Number Of Files Embedded Icon(Malware): ", iconEmbededM       
Beispiel #3
0
def test(exePath):
    import win32ui
    import win32gui
    import win32con
    import win32api

    # ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    # ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
    ico_x = 32
    ico_y = 32

    # exePath = "c:/windows/system32/shell32.dll"
    large, small = win32gui.ExtractIconEx(exePath, 0)
    useIcon = large[0]
    destroyIcon = small[0]
    win32gui.DestroyIcon(destroyIcon)
    print('dd', (useIcon))

    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
    hdc = hdc.CreateCompatibleDC()

    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), useIcon)
    savePath = "d:/test.bmp"
    hbmp.SaveBitmapFile(hdc, savePath)
 def __init__(self):
     message_map = {
         win32con.WM_DESTROY: self.on_destroy,
         win32con.WM_COMMAND: self.on_command,
         win32con.WM_USER + 20: self.on_taskbar_notify
     }
     # Register the Window class.
     wc = win32gui.WNDCLASS()
     hinst = wc.hInstance = win32api.GetModuleHandle(None)
     wc.lpszClassName = "TimeCounter"
     wc.lpfnWndProc = message_map  # could also specify a wndproc.
     classAtom = win32gui.RegisterClass(wc)
     # Create the Window.
     style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
     self.hwnd = win32gui.CreateWindow(classAtom, "Taskbar", style, 0, 0,
                                       win32con.CW_USEDEFAULT,
                                       win32con.CW_USEDEFAULT, 0, 0, hinst,
                                       None)
     win32gui.UpdateWindow(self.hwnd)
     # icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
     try:
         shell_dll = os.path.join(win32api.GetSystemDirectory(),
                                  "shell32.dll")
         large, small = win32gui.ExtractIconEx(shell_dll, 265, 1)
         hicon = small[0]
         win32gui.DestroyIcon(large[0])
     except:
         hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
     flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
     nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon,
            "Starting...")
     win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)
     global handel
     handel = self.hwnd
Beispiel #5
0
def save_icon(icon_path, save_path):
    if icon_path == "Error: No path found":
        return False

    icon_path = icon_path.replace("\\", "/")
    try:
        iconX = win32api.GetSystemMetrics(win32con.SM_CXICON)
        iconY = win32api.GetSystemMetrics(win32con.SM_CXICON)

        large, small = win32gui.ExtractIconEx(icon_path, 0)
        win32gui.DestroyIcon(small[0])

        hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap(hdc, iconX, iconX)
        hdc = hdc.CreateCompatibleDC()

        hdc.SelectObject(hbmp)
        hdc.DrawIcon((0, 0), large[0])

        bmpstr = hbmp.GetBitmapBits(True)
        from PIL import Image
        img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1)
        extrema = img.convert("L").getextrema()
        if "Chrome" in icon_path:
            pass
            # print("TEST")
        if extrema[1] < 250:
            img.save(save_path)
        return True
    except Exception as e:
        # print("Error:")
        # print(e)
        return False
Beispiel #6
0
def extract_icon(exefilename):
    """Get the first resource icon from win32 exefilename and returns it a s PNG bytes array"""
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)

    large, small = win32gui.ExtractIconEx(exefilename,0)
    temp_dir = tempfile.mkdtemp()
    try:
        hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap( hdc, ico_x, ico_x )
        hdc = hdc.CreateCompatibleDC()

        hdc.SelectObject( hbmp )
        hdc.DrawIcon( (0,0), large[0] )

        bmp_temp = os.path.join(temp_dir,"icon.bmp")
        hbmp.SaveBitmapFile(hdc,bmp_temp)

        im = Image.open(bmp_temp)
        png_temp = os.path.join(temp_dir,"icon.png")
        with open(png_temp,'wb') as png:
            im.save(png, "PNG")
            result = open(png_temp,'rb').read()

        return result
    finally:
        win32gui.DestroyIcon(small[0])
        win32gui.DestroyIcon(large[0])
        if os.path.isdir(temp_dir):
            shutil.rmtree(temp_dir)
Beispiel #7
0
    def get_icon(filepath: Optional[str],
                 icon_save_directory: Optional[str] = None) -> Optional[str]:
        if not filepath:
            return None  # no file path to save the icon from

        # TODO: Get icons of different sizes.
        small, large = win32gui.ExtractIconEx(filepath, 0, 10)
        if len(large) <= 0:
            return None  # no icon to extract

        if len(small) > 0:
            win32gui.DestroyIcon(small[0])  # get rid of the small one

        hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y)
        hdc = hdc.CreateCompatibleDC()
        hdc.SelectObject(hbmp)
        hdc.DrawIcon((0, 0), large[0])

        executable_path = Path(filepath)
        icon_path = icon_name = f"icon_{executable_path.name}.bmp"
        if icon_save_directory:
            icon_path = str((Path(icon_save_directory) / icon_name).resolve())
        hbmp.SaveBitmapFile(hdc, icon_path)
        with Image.open(icon_path) as img:
            buffered = BytesIO()
            img.save(buffered, format="PNG")
            image_string = base64.b64encode(buffered.getvalue()).decode()
        if not icon_save_directory:
            Path(icon_path).unlink()
        return image_string
Beispiel #8
0
def ExtractIcon(filename):
    large, small = win32gui.ExtractIconEx(filename, 0)
    # win32gui.DestroyIcon(small[0])
    h = bitmapFromHIcon(large[0])
    print h
    pixmap = QtGui.QPixmap.fromWinHBITMAP(h, 2)
    pixmap.save("large.ico", "ico")
    pass
Beispiel #9
0
 def icon_from_exec_win(self, path):
     large, small = win32gui.ExtractIconEx(path, 0)
     for i in small:
         win32gui.DestroyIcon(i)
     pixmap = QtWin.fromHBITMAP(self.bitmapFromHIcon(large[0]), 1)
     for i in large:
         win32gui.DestroyIcon(i)
     return QtGui.QIcon(pixmap)
Beispiel #10
0
	def make_icon(self, link_path, save_path):
		"""获取exe文件的图标"""
		if os.path.splitext(link_path)[-1].lower() == ".exe":  # 此处程序后缀有可能为大写的EXE
			large, small = win32gui.ExtractIconEx(link_path, 0)
			win32gui.DestroyIcon(small[0])
			self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.__bitmap_from_hIcon(large[0]), 2)
			self.pixmap.save(save_path, "ico")
			return True
		else:
			return False
Beispiel #11
0
    def dispalyName_Icon(self):
        i = 0
        for key in self.numreg[1].keys():
            try:  # ico 来自exe
                ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
                ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
                large, small = win32gui.ExtractIconEx(
                    self.numreg[1][key]['exe'], 0)
                #exemenu=self.numreg[1][key]['exe']
                useIcon = large[0]
                destroyIcon = small[0]
                win32gui.DestroyIcon(destroyIcon)

                hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
                hbmp = win32ui.CreateBitmap()
                hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y)
                hdc = hdc.CreateCompatibleDC()

                hdc.SelectObject(hbmp)
                hdc.DrawIcon((0, 0), useIcon)

                #savePath = "d:/test.bmp"
                #savePath = "d:/"
                #hbmp.SaveBitmapFile(hdc, savePath)

                bmpstr = hbmp.GetBitmapBits(True)
                img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA',
                                       0, 1)
                cwd = os.getcwd()
                img.save(cwd + '/icon.png')
                self.pixmap = 'icon.png'

            #except Exception as e:  #ico 来自 icon
            except:
                #ico 来自 icon
                # 判断ico文件是否存在
                if 'icon' in self.numreg[1][key] and os.path.isfile(
                        self.numreg[1][key]['icon']):
                    self.pixmap = QPixmap(self.numreg[1][key]['icon'])
                    iconMenu = self.numreg[1][key]['icon']
                    #split = iconMenu.split('\\')
                    #exeMenu ='\\'.join(split[:-1])
                else:  # 不存在ico文件给定默认图标
                    self.pixmap = 'SoftwareTool.png'
                    #exeMenu = ''

            DisplayName = self.numreg[1][key]['DisplayName'].encode('utf-8')
            DisplayName = str(DisplayName, encoding='utf-8')
            newitem = QTableWidgetItem(QIcon(self.pixmap), DisplayName)
            #newitem1 = QTableWidgetItem(filesize)
            #为每个表格内添加数据
            self.tableWidget.setItem(i, 0, newitem)
            #self.tableWidget.setItem(i,1,newitem1)
            i += 1
Beispiel #12
0
    def set_icon(self, path):
        if platform.system() == "Windows":
            # Get the icons in different sizes from the binary
            try:
                large, small = win32gui.ExtractIconEx(path, 0, 10)
            except pywintypes.error:
                return

            # Convert it into a pixmap
            if large:
                pixmap: QPixmap = QtWin.fromHICON(large[0])
                self.game_item_widget.iconLabel.setPixmap(
                    QPixmap.scaledToHeight(pixmap, 32))
            tuple(map(win32gui.DestroyIcon, small + large))
Beispiel #13
0
    def _SetupList(self):
        child_style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER | win32con.WS_HSCROLL | win32con.WS_VSCROLL
        child_style |= commctrl.LVS_SINGLESEL | commctrl.LVS_SHOWSELALWAYS | commctrl.LVS_REPORT
        self.hwndList = win32gui.CreateWindow("SysListView32", None,
                                              child_style, 0, 0, 100, 100,
                                              self.hwnd, IDC_LISTBOX,
                                              self.hinst, None)

        child_ex_style = win32gui.SendMessage(
            self.hwndList, commctrl.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
        child_ex_style |= commctrl.LVS_EX_FULLROWSELECT
        win32gui.SendMessage(self.hwndList,
                             commctrl.LVM_SETEXTENDEDLISTVIEWSTYLE, 0,
                             child_ex_style)

        # Add an image list - use the builtin shell folder icon - this
        # demonstrates the problem with alpha-blending of icons on XP if
        # winxpgui is not used in place of win32gui.
        il = win32gui.ImageList_Create(
            win32api.GetSystemMetrics(win32con.SM_CXSMICON),
            win32api.GetSystemMetrics(win32con.SM_CYSMICON),
            commctrl.ILC_COLOR32 | commctrl.ILC_MASK,
            1,  # initial size
            0)  # cGrow

        shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll")
        large, small = win32gui.ExtractIconEx(shell_dll, 4, 1)
        win32gui.ImageList_ReplaceIcon(il, -1, small[0])
        win32gui.DestroyIcon(small[0])
        win32gui.DestroyIcon(large[0])
        win32gui.SendMessage(self.hwndList, commctrl.LVM_SETIMAGELIST,
                             commctrl.LVSIL_SMALL, il)

        # Setup the list control columns.
        lvc = LVCOLUMN(mask=commctrl.LVCF_FMT | commctrl.LVCF_WIDTH
                       | commctrl.LVCF_TEXT | commctrl.LVCF_SUBITEM)
        lvc.fmt = commctrl.LVCFMT_LEFT
        lvc.iSubItem = 1
        lvc.text = "Title"
        lvc.cx = 200
        win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0,
                             lvc.toparam())
        lvc.iSubItem = 0
        lvc.text = "Order"
        lvc.cx = 50
        win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0,
                             lvc.toparam())

        win32gui.UpdateWindow(self.hwnd)
Beispiel #14
0
 def get_icon(self):
     try:
         icons_large, icons_small = win32gui.ExtractIconEx(self.path, 0)
     except pywintypes.error:
         logger.warning('ExtractIconEx failed: title={}, path={}'.format(
             repr(self.title), self.path))
         return QPixmap()
     icons = icons_large + icons_small
     if not icons:
         logger.warning('no icons: {}'.format(self.path))
         return QPixmap()
     pixmap = hicon2pixmap(icons[0])
     for hicon in icons:
         win32gui.DestroyIcon(hicon)
     return pixmap
def saveExecutableIcon(exe, out="tmp/icon.png"):
    shell = win32com.client.Dispatch("WScript.Shell")
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
    large, small = win32gui.ExtractIconEx(exe, 0)
    win32gui.DestroyIcon(small[0])
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), large[0])
    hbmp.SaveBitmapFile(hdc, out)
    img = Image.open(out)
    img.save(out, 'png')
	def prep(self):
		ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
		ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
		lr, sm = win32gui.ExtractIconEx(self.executable,0)
		win32gui.DestroyIcon(lr[0])
		hicon = sm[0]
		hdcBitmap = win32gui.CreateCompatibleDC(0)
		hdcScreen = win32gui.GetDC(0)
		hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
		hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
		brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
		win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
		win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
		win32gui.SelectObject(hdcBitmap, hbmOld)
		win32gui.DeleteDC(hdcBitmap)
		return hbm
Beispiel #17
0
    def __init__(self, parent, name, commands=None, icon_path=None):
        self.parent = parent
        self.name = name
        self.WM_NOTIFY = win32con.WM_USER + 20

        wndproc = {
            win32con.WM_DESTROY: self.on_destroy,
            win32con.WM_COMMAND: self.on_command,
            self.WM_NOTIFY: self.on_tray_notify,
        }

        wc = win32gui.WNDCLASS()
        wc.hInstance = hinst = win32api.GetModuleHandle(None)
        wc.lpszClassName = name.title()
        wc.lpfnWndProc = wndproc
        try:
            class_atom = win32gui.RegisterClass(wc)
        except:
            pass
        self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "",
                                          win32con.WS_POPUP, 0, 0, 1, 1, 0, 0,
                                          hinst, None)
        win32gui.UpdateWindow(self.hwnd)

        if icon_path is not None and os.path.isfile(icon_path):
            icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
            hicon = win32gui.LoadImage(None, icon_path, win32con.IMAGE_ICON, 0,
                                       0, icon_flags)
        else:
            shell_dll = os.path.join(win32api.GetSystemDirectory(),
                                     "shell32.dll")
            large, small = win32gui.ExtractIconEx(shell_dll, 19, 1)  #19 or 76
            hicon = small[0]
            win32gui.DestroyIcon(large[0])
        self.hicon = hicon

        flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP | win32gui.NIF_INFO
        nid = (self.hwnd, 0, flags, self.WM_NOTIFY, self.hicon, self.name)
        win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)

        self.next_command_id = 1000
        self.commands = {}
        self.register_command('Exit',
                              lambda: win32gui.DestroyWindow(self.hwnd))
        if commands is not None:
            for n, f in commands[::-1]:
                self.register_command(n, f)
Beispiel #18
0
def save_app_icon(app_path, save_path, save_gray_path):
    large, small = win32gui.ExtractIconEx(app_path, 0)
    win32gui.DestroyIcon(small[0])
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, 32, 32)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), large[0])
    bmpstr = hbmp.GetBitmapBits(True)
    img = Image.frombuffer(
        'RGBA',
        (32, 32),
        bmpstr, 'raw', 'BGRA', 0, 1
    )
    img.save(save_path)
    img = img.convert("LA")
    img.save(save_gray_path)
Beispiel #19
0
def simple_load_icon(module, index, as_data=False, size=ICON_SIZE):
    ' Use the win32 API ExtractIcon to load the icon. This restricts icon size to 32x32, but has less chance of failing '
    try:
        large_icons, small_icons = win32gui.ExtractIconEx(module, index, 10)
    except pywintypes.error as err:
        if err.winerror != winerror.ERROR_FILE_NOT_FOUND:
            raise
        prints('File %r does not exist, cannot load icon' % module)
        return
    icons = large_icons + small_icons
    try:
        if icons:
            must_use_qt()
            pixmap = copy_to_size(QtWin.fromHICON(icons[0]), size=size)
            if as_data:
                return pixmap_to_data(pixmap)
            return QIcon(pixmap)
    finally:
        tuple(map(win32gui.DestroyIcon, icons))
Beispiel #20
0
def iconextract(path, filename):
    try:
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
        large, small = win32gui.ExtractIconEx(path, 0)
        win32gui.DestroyIcon(large[0])
        hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
        hdc = hdc.CreateCompatibleDC()
        hdc.SelectObject(hbmp)
        hdc.DrawIcon((0, 0), small[0])
        hbmp.SaveBitmapFile(hdc, filename + ".bmp")
        img = Image.open(filename + ".bmp")
        img.save(filename + '.ico')
        for p in Path(".").glob("*.bmp"):
            p.unlink()
    except:
        pass
def extractExeIcons(exePath, exeName):
    # desktop = os.path.join(os.environ['USERPROFILE'], "Desktop")
    iconPath = os.getcwd() + r'\icons'
    if not os.path.exists(iconPath):
        os.mkdir(iconPath)

    try:
        path = exePath.replace("\\", "/")
        if "Discord" in path:
            path = os.environ['USERPROFILE'].replace(
                "\\", "/") + "/AppData/Local/Discord/app.ico"
        if "valorant" in path:
            path = os.environ['systemdrive'].replace(
                "\\", "/"
            ) + "/ProgramData/Riot Games/Metadata/valorant.live/valorant.live.ico"
        if "Teams" in path:
            path = os.environ['USERPROFILE'].replace(
                "\\", "/") + "/AppData/Local/Microsoft/Teams/app.ico"
        icoX = win32api.GetSystemMetrics(win32con.SM_CXICON)
        icoY = win32api.GetSystemMetrics(win32con.SM_CYICON)

        large, small = win32gui.ExtractIconEx(path, 0)
        win32gui.DestroyIcon(small[0])

        hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap(hdc, icoX, icoY)
        hdc = hdc.CreateCompatibleDC()

        hdc.SelectObject(hbmp)
        hdc.DrawIcon((0, 0), large[0])

        bmpstr = hbmp.GetBitmapBits(True)
        img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1)

        new_img_location = iconPath + '\\' + exeName + '.ico'
        img.save(new_img_location, format("ico"))
        new_img_location = new_img_location.replace("\\", "/")

        hbmp.SaveBitmapFile(hdc, iconPath + '\\' + exeName + '.bmp')
    except:
        new_img_location = None
    return new_img_location
Beispiel #22
0
    def __init__(self, parent=None):
        super(ListDialog, self).__init__(parent)
        self.contentsWidget = QtGui.QListWidget()
        self.contentsWidget.setViewMode(QtGui.QListView.IconMode)
        self.contentsWidget.setIconSize(QtCore.QSize(96, 84))  # Icon 大小
        self.contentsWidget.setMovement(
            QtGui.QListView.Static)  # Listview不让列表拖动
        self.contentsWidget.setMaximumWidth(800)  # 最大宽度
        self.contentsWidget.setSpacing(15)  # 间距大小
        winrege = winregeditor()
        self.numreg = winrege.getreg()
        for key in self.numreg.keys():
            Atem = QtGui.QListWidgetItem(self.contentsWidget)
            try:  # ico 来自exe
                large, small = win32gui.ExtractIconEx(self.numreg[key]['exe'],
                                                      0)
                exeMenu = self.numreg[key]['exe']
                win32gui.DestroyIcon(small[0])
                self.pixmap = QtGui.QPixmap.fromWinHBITMAP(
                    self.bitmapFromHIcon(large[0]), 2)
            except Exception as err:  # ico 来自 icon
                if self.numreg[key].has_key('icon') and os.path.isfile(
                        self.numreg[key]['icon']):  # 判断ico文件是否存在
                    self.pixmap = QtGui.QPixmap(self.numreg[key]['icon'])
                    iconMenu = self.numreg[key]['icon']
                    split = iconMenu.split('\\')
                    exeMenu = '\\'.join(split[:-1])
                else:  # 不存在ico文件给定默认图标
                    self.pixmap = ':default.png'
                    exeMenu = ''

                Atem.setIcon(QtGui.QIcon(self.pixmap))
                Atem.setFlags(QtCore.Qt.ItemIsSelectable
                              | QtCore.Qt.ItemIsEnabled)
                Atem.setTextAlignment(QtCore.Qt.AlignHCenter)
                Atem.setData(QtCore.Qt.UserRole, exeMenu)
                DisplayName = self.numreg[key]['DisplayName'].encode('utf-8')
                Atem.setToolTip(u"" + DisplayName)  # tip 显示
                if len(DisplayName) >= 6:
                    DisplayName = DisplayName.decode('utf8')[0:6].encode(
                        'utf8') + '…'
                Atem.setText(u"" + DisplayName)
Beispiel #23
0
def getAndWriteProgImage(input_path, output_path):

    input_path = input_path.replace("\\", "/")
    icoX = win32api.GetSystemMetrics(win32con.SM_CXICON)
    icoY = win32api.GetSystemMetrics(win32con.SM_CXICON)

    large, small = win32gui.ExtractIconEx(input_path, 0)
    win32gui.DestroyIcon(small[0])

    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, icoX, icoX)
    hdc = hdc.CreateCompatibleDC()

    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), large[0])

    bmpstr = hbmp.GetBitmapBits(True)
    img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1)
    img.save(output_path)
Beispiel #24
0
def get_icon(exe):
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
    large, small = win32gui.ExtractIconEx(exe, 0)
    if len(small) == 0:
        return False
    win32gui.DestroyIcon(large[0])
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    icon_bmp = win32ui.CreateBitmap()
    icon_bmp.CreateCompatibleBitmap(hdc, ico_x, ico_y)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(icon_bmp)
    hdc.DrawIcon((0, 0), small[0])  # draw the icon before getting bits
    icon_info = icon_bmp.GetInfo()
    icon_buffer = icon_bmp.GetBitmapBits(True)
    icon = Image.frombuffer('RGB',
                            (icon_info['bmWidth'], icon_info['bmHeight']),
                            icon_buffer, 'raw', 'BGRX', 0, 1)
    win32gui.DestroyIcon(small[0])
    return icon
Beispiel #25
0
    def _create(self):
        # param1 に NULL(0) を指定すると
        # 現在のプロセスを作成するために使われたファイルのパスを取得.
        self_filename = win32api.GetModuleFileName(0)

        self.hicon = win32gui.ExtractIconEx(self_filename, 0, 1)[0][0]

        # param2 は扱うアイコンの識別子.
        # 扱うアイコンは 1 つなので適当にした.
        notifyicondata = (
            self.hwnd,
            0,
            win32gui.NIF_MESSAGE | win32gui.NIF_ICON | win32gui.NIF_TIP,
            self.callback_message,
            self.hicon,
            self.hovertext
        )
        win32gui.Shell_NotifyIcon(
            win32gui.NIM_ADD,
            notifyicondata
        )
Beispiel #26
0
 def getGameItem(self, name, time, num, game, st):
     path = game.path
     gameItem = gameItemUI.GameItem(self.ui.centralwidget)
     try:
         name = name.decode('utf-8')
     except:
         pass
     gameItem.nameLabe.setText(name)
     h, m, s = st.getPrintTime(time)
     allTimestr = '总共运行:%s小时%s分%s秒' % (h, m, s)
     allTimestr = allTimestr.decode('GBK')
     gameItem.timeLabe.setText(allTimestr)
     gameItem.setToolTip4All(allTimestr)
     if os.path.exists(path):
         large, small = win32gui.ExtractIconEx(game.path, 0)
         pixmap = QPixmap.fromWinHBITMAP(self.bitmapFromHIcon(large[0]), 2)
         pixmap.save("./data/%s.ico" % num, "ico")
     if os.path.exists("./data/%s.ico" % num):
         gameItem.startButton.setIcon(QIcon("./data/%s.ico" % num))
     gameItem.connect(gameItem.startButton, SIGNAL("clicked()"),
                      game.startGame)
     return gameItem
Beispiel #27
0
def init_app_links(apps_dir, badIcons, iconList):
    init_params = []
    for path, (target, icon,
               shortcut_descr) in _get_app_links(apps_dir).iteritems():
        if target.lower().find(u''
                               r'installer\{') != -1:  # msi shortcuts: dc0c8de
            target = path
        else:
            target = GPath(target)
        if not target.exists(): continue
        # Target exists - extract path, icon and shortcut_descr
        # First try a custom icon #TODO(ut) docs - also comments methods here!
        fileName = u'%s%%i.png' % path.sbody
        customIcons = [apps_dir.join(fileName % x) for x in (16, 24, 32)]
        if customIcons[0].exists():
            icon = customIcons
        # Next try the shortcut specified icon
        else:
            icon, idex = icon.split(u',')
            if icon == u'':
                if target.cext == u'.exe':
                    if win32gui and win32gui.ExtractIconEx(target.s, -1):
                        # -1 queries num of icons embedded in the exe
                        icon = target
                    else:  # generic exe icon, hardcoded and good to go
                        icon, idex = os.path.expandvars(
                            u'%SystemRoot%\\System32\\shell32.dll'), u'2'
                else:
                    icon, idex = _get_default_app_icon(idex, target)
            icon = GPath(icon)
            if icon.exists():
                fileName = u';'.join((icon.s, idex))
                icon = iconList(GPath(fileName))
                # Last, use the 'x' icon
            else:
                icon = badIcons
        init_params.append((path, icon, shortcut_descr))
    return init_params
Beispiel #28
0
    def __init__(self, cmd, tooltip):
        self.cmd = cmd
        message_map = {
            win32con.WM_DESTROY: self.onDestroy,
            win32con.WM_COMMAND: self.onCommand,
            WM_TASKBARNOTIFY: self.onTaskbarNotify,
        }
        # Register the Window class.
        wc = win32gui.WNDCLASS()
        wc.hInstance = win32api.GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbarDemo"
        wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
        wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
        wc.hbrBackground = win32con.COLOR_WINDOW
        wc.lpfnWndProc = message_map  # could also specify a wndproc.
        classAtom = win32gui.RegisterClass(wc)
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = win32gui.CreateWindow( classAtom, "Taskbar Demo", style, \
                    0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
                    0, 0, wc.hInstance, None)
        win32gui.UpdateWindow(self.hwnd)

        hProcess, hThread, dwProcessId, dwThreadId = win32process.CreateProcess(
            None, self.cmd, None, None, 0, 0, None, None,
            win32process.STARTUPINFO())
        self.hProcess = hProcess
        try:
            hicon, small = win32gui.ExtractIconEx(
                win32api.GetModuleFileName(0), 0)
            win32gui.DestroyIcon(small[0])
            #hicon = pywintypes.HANDLE(hicon[0])
            hicon = hicon[0]
        except IndexError:
            hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
        self.hicon = hicon
        self.tooltip = tooltip
        self.show()
Beispiel #29
0
def windowsIconGetter(path,
                      nIcon=0,
                      exeOrDll=True):  #It's can be exe, dll, or already ico

    if os.path.isfile(path):
        dst = cStringIO.StringIO()
        if exeOrDll:
            large, small = win32gui.ExtractIconEx(path, nIcon)
            win32gui.DestroyIcon(small[0])
            #creating a destination memory DC
            hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
            hbmp = win32ui.CreateBitmap()
            hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
            hdc = hdc.CreateCompatibleDC()
            hdc.SelectObject(hbmp)
            #set the background in white
            hdc.FillSolidRect((0, 0, ico_x, ico_x), 0xffffff)
            #draw a icon in it
            hdc.DrawIcon((0, 0), large[0])
            win32gui.DestroyIcon(large[0])
            #convert picture in JPEG
            hbmp.SaveBitmapFile(hdc, dirTmpFile)
            im = Image.open(dirTmpFile)
        else:
            im = Image.open(path)

        try:
            im.save(dst, "JPEG")
        except IOError:
            return None

        dst.seek(0)
        return base64.b64encode(dst.read())

    else:
        return None
Beispiel #30
0
 def handle_select_file(self):
     print("选择文件")
     filename, fileType = QFileDialog.getOpenFileName(
         self, "选择运行的文件", "", "exe(*.exe)")
     print("select file" + filename)
     large, small = win32gui.ExtractIconEx(filename, 0)