Exemple #1
0
 def OnDisconnection(self, mode, custom):
     dbg_print('ClamWin - Disconnecting from Outlook')
     try:
         if hLibClamAV != 0:
             win32api.FreeLibrary(hLibClamAV)
         if hLibClamUnrar != 0:
             win32api.FreeLibrary(hLibClamUnrar)
         if hLibClamUnrar_iface != 0:
             win32api.FreeLibrary(hLibClamUnrar_iface)
     except Exception, e:
         print str(e)
def StockToolInterface(mStockData):
    try:
        dll = CDLL(
            'D:\\MyProjects\\win_project\\DataFrameTool\\x64\\Release\\DataFrameTool.dll'
        )
        mStockData.to_clipboard()
        b = dll.ToolInterface(1)
        result = pd.read_clipboard()
        win32api.FreeLibrary(dll._handle)
        return result
    except:
        print 'Error'
        win32api.FreeLibrary(dll._handle)
        return mStockData
Exemple #3
0
    def test_free_library(self):
        with self.load_library(win32api) as handle:
            self.assertTrue(win32api.FreeLibrary(handle) is None)
            self.assertNotEqual(self.module.FreeLibrary(handle), 0)

        with self.assertRaises(error):
            self.module.FreeLibrary(-3)
Exemple #4
0
def CopyIcons(dstpath, srcpath):
    import os.path, string
    index = None
    try:
        srcpath, index = map(string.strip, string.split(srcpath, ','))
        index = int(index)
    except:
        pass
    print "I: PATH, INDEX", srcpath, index
    srcext = os.path.splitext(srcpath)[1]
    if string.lower(srcext) == '.ico':
        return CopyIcons_FromIco(dstpath, srcpath)
    if index is not None:
        print "I: Updating icons from", srcpath, ", %d to" % index, dstpath
    else:
        print "I: Updating icons from", srcpath, "to", dstpath
    import win32api  #, win32con
    hdst = win32api.BeginUpdateResource(dstpath, 0)
    hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
    if index is None:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
    elif index >= 0:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
    else:
        grpname = -index
    data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
    win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
    for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
        data = win32api.LoadResource(hsrc, RT_ICON, iconname)
        win32api.UpdateResource(hdst, RT_ICON, iconname, data)
    win32api.FreeLibrary(hsrc)
    win32api.EndUpdateResource(hdst, 0)
Exemple #5
0
 def closePort(self):
     try:
         win32api.FreeLibrary(self.dll._handle)
         return True
     except Exception:
         print("KEY断开失败")
         return False
Exemple #6
0
def load_icon(module, index, as_data=False, size=ICON_SIZE):
    handle = win32api.LoadLibraryEx(module, 0, 0x20 | 0x2)
    try:
        ids = win32api.EnumResourceNames(handle, win32con.RT_GROUP_ICON)
        grp_id = -index if index < 0 else ids[index]
        data = win32api.LoadResource(handle, win32con.RT_GROUP_ICON, grp_id)
        pos = 0
        reserved, idtype, count = struct.unpack_from(b'<HHH', data, pos)
        pos += 6
        fmt = b'<BBBBHHIH'
        ssz = struct.calcsize(fmt)
        icons = []
        Icon = namedtuple('Icon', 'size width height id')
        while count > 0:
            count -= 1
            width, height, color_count, reserved, planes, bitcount, isize, icon_id = struct.unpack_from(
                fmt, data, pos)
            icons.append(Icon(isize, width, height, icon_id))
            pos += ssz
        # Unfortunately we cannot simply choose the icon with the largest
        # width/height as the width and height are not recorded for PNG images
        pixmaps = []
        for icon in icons:
            ans = read_icon(handle, icon)
            if ans is not None and not ans.isNull():
                pixmaps.append(ans)
        pixmaps.sort(key=lambda p: p.size().width(), reverse=True)
        pixmap = copy_to_size(pixmaps[0], size=size)
        if as_data:
            pixmap = pixmap_to_data(pixmap)
        return pixmap
    finally:
        win32api.FreeLibrary(handle)
Exemple #7
0
def decode(pathnm):
    h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
    nm = win32api.EnumResourceNames(h, RT_VERSION)[0]
    data = win32api.LoadResource(h, RT_VERSION, nm)
    vs = VSVersionInfo()
    j = vs.fromRaw(data)
    if TEST:
        print vs
        if data[:j] != vs.toRaw():
            print "AAAAAGGHHHH"
        txt = repr(vs)
        glbls = {}
        glbls['VSVersionInfo'] = VSVersionInfo
        glbls['FixedFileInfo'] = FixedFileInfo
        glbls['StringFileInfo'] = StringFileInfo
        glbls['StringTable'] = StringTable
        glbls['StringStruct'] = StringStruct
        glbls['VarFileInfo'] = VarFileInfo
        glbls['VarStruct'] = VarStruct
        vs2 = eval(txt + '\n', glbls)
        if vs.toRaw() != vs2.toRaw():
            print
            print 'reconstruction not the same!'
            print vs2
    win32api.FreeLibrary(h)
    return vs
Exemple #8
0
def _LoadDll(dll_path):
  """Tries to load, hence initializing, the given DLL.

  Args:
    dll_path: the path to the DLL to test.

  Returns:
    True on success, False on failure.
  """
  mode = (win32con.SEM_FAILCRITICALERRORS |
          win32con.SEM_NOALIGNMENTFAULTEXCEPT |
          win32con.SEM_NOGPFAULTERRORBOX |
          win32con.SEM_NOOPENFILEERRORBOX)
  old_mode = win32api.SetErrorMode(mode)
  try:
    handle = win32api.LoadLibrary(dll_path)
    if not handle:
      return False
    win32api.FreeLibrary(handle)
  except pywintypes.error as e:  # pylint: disable=E1101
    _LOGGER.error('Error: %s', e)
    return False
  finally:
    win32api.SetErrorMode(old_mode)
  return True
Exemple #9
0
 def closeport(self):
     try:
         self.dll.CT_close(self.hDev)
         win32api.FreeLibrary(self.dll._handle)
         return label_pass
     except Exception:
         raise DeviceError('Close Device Failed')
Exemple #10
0
def get_ppid():
    # NtQueryInformationProcess的用法参考自:
    # http://stackoverflow.com/questions/6587036/alternative-to-psutil-processpid-name
    ntdll = ctypes.windll.LoadLibrary('ntdll.dll')
    if not ntdll:
        return 0

    try:
        pid = win32api.GetCurrentProcessId()
        if not pid:
            return 0

        hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False,
                                     pid)
        if not hproc:
            return 0

        buflen = ctypes.sizeof(PROCESS_BASIC_INFORMATION)
        buf = ctypes.c_char_p('\0' * buflen)
        ret = ntdll.NtQueryInformationProcess(int(hproc),
                                              ProcessBasicInformation, buf,
                                              buflen, None)
        if ret != STATUS_SUCCESS:
            return 0

        pbuf = ctypes.cast(buf, ctypes.POINTER(PROCESS_BASIC_INFORMATION))
        ppid = pbuf[0].Reserved3
        return ppid

    finally:
        win32api.FreeLibrary(ntdll._handle)
Exemple #11
0
def decode(pathnm):
    h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
    nm = win32api.EnumResourceNames(h, pefile.RESOURCE_TYPE['RT_VERSION'])[0]
    data = win32api.LoadResource(h, pefile.RESOURCE_TYPE['RT_VERSION'], nm)
    vs = VSVersionInfo()
    j = vs.fromRaw(data)
    win32api.FreeLibrary(h)
    return vs
def CopyIcons(dstpath, srcpath):
    import os.path

    if type(srcpath) in StringTypes:
        srcpath = [srcpath]

    def splitter(s):
        try:
            srcpath, index = s.split(',')
            return srcpath.strip(), int(index)
        except ValueError:
            return s, None

    srcpath = list(map(splitter, srcpath))
    logger.info("SRCPATH %s", srcpath)

    if len(srcpath) > 1:
        # At the moment, we support multiple icons only from .ico files
        srcs = []
        for s in srcpath:
            e = os.path.splitext(s[0])[1]
            if e.lower() != '.ico':
                raise ValueError(
                    'Multiple icons supported only from .ico files')
            if s[1] is not None:
                raise ValueError('index not allowed for .ico files')
            srcs.append(s[0])
        return CopyIcons_FromIco(dstpath, srcs)

    srcpath, index = srcpath[0]
    srcext = os.path.splitext(srcpath)[1]
    if srcext.lower() == '.ico':
        return CopyIcons_FromIco(dstpath, [srcpath])
    if index is not None:
        logger.info("Updating icons from %s, %d to %s", srcpath, index,
                    dstpath)
    else:
        logger.info("Updating icons from %s to %s", srcpath, dstpath)
    import win32api  #, win32con
    hdst = win32api.BeginUpdateResource(dstpath, 0)
    hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
    if index is None:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
    elif index >= 0:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
    else:
        grpname = -index
    data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
    win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
    for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
        data = win32api.LoadResource(hsrc, RT_ICON, iconname)
        win32api.UpdateResource(hdst, RT_ICON, iconname, data)
    win32api.FreeLibrary(hsrc)
    win32api.EndUpdateResource(hdst, 0)
Exemple #13
0
def FormatMessage(eventLogRecord, logType="Application"):
    """Given a tuple from ReadEventLog, and optionally where the event
    record came from, load the message, and process message inserts.

    Note that this function may raise win32api.error.  See also the
    function SafeFormatMessage which will return None if the message can
    not be processed.
    """

    # From the event log source name, we know the name of the registry
    # key to look under for the name of the message DLL that contains
    # the messages we need to extract with FormatMessage. So first get
    # the event log source name...
    keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (
        logType,
        eventLogRecord.SourceName,
    )

    # Now open this key and get the EventMessageFile value, which is
    # the name of the message DLL.
    handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
    try:
        dllNames = win32api.RegQueryValueEx(handle,
                                            "EventMessageFile")[0].split(";")
        # Win2k etc appear to allow multiple DLL names
        data = None
        for dllName in dllNames:
            try:
                # Expand environment variable strings in the message DLL path name,
                # in case any are there.
                dllName = win32api.ExpandEnvironmentStrings(dllName)

                dllHandle = win32api.LoadLibraryEx(
                    dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
                try:
                    data = win32api.FormatMessageW(
                        win32con.FORMAT_MESSAGE_FROM_HMODULE,
                        dllHandle,
                        eventLogRecord.EventID,
                        langid,
                        eventLogRecord.StringInserts,
                    )
                finally:
                    win32api.FreeLibrary(dllHandle)
            except win32api.error:
                pass  # Not in this DLL - try the next
            if data is not None:
                break
    finally:
        win32api.RegCloseKey(handle)
    return data or ""  # Don't want "None" ever being returned.
Exemple #14
0
def load_string_resource(pointer):
    """Resolve a @dllname,ordinal string resource pointer"""

    if pointer[0] != "@":
        return pointer

    resfile, resid = pointer[1:].split(",")
    resid = int(resid)

    hRes = Api.LoadLibraryEx(resfile, 0, Con.LOAD_LIBRARY_AS_DATAFILE)
    val = Api.LoadString(hRes, -resid, 1024)
    Api.FreeLibrary(hRes)

    return val.split('\x00', 1)[0]
    def _loadModuleInternal(module, cwd):
        '''
		Loads a module by calling `LoadLibrary()` directly inside the Python interpreter
		'''
        origCwd = os.getcwd()
        os.chdir(cwd)
        try:
            handle = win32api.LoadLibrary(module)
            win32api.FreeLibrary(handle)
            return 0
        except Exception as e:
            return e.winerror
        finally:
            os.chdir(origCwd)
Exemple #16
0
    def __del__(self):
        if self._module:
            win32api.FreeLibrary(self._module)
            self._module = None

        if self._update_handle:
            _LOGGER.info('Canceling edits to "%s".', self.input_file)
            win32api.EndUpdateResource(self._update_handle, False)
            self._update_handle = None

        if self._temp_dir:
            _LOGGER.info('Removing temporary directory "%s".', self._temp_dir)
            shutil.rmtree(self._temp_dir)
            self._temp_dir = None
Exemple #17
0
def GetResources(filename, types=None, names=None, languages=None):
    """
    Get resources from dll/exe file.

    types = a list of resource types to search for (None = all)
    names = a list of resource names to search for (None = all)
    languages = a list of resource languages to search for (None = all)
    Return a dict of the form {type_: {name: {language: data}}} which
    might also be empty if no matching resources were found.
    """
    hsrc = win32api.LoadLibraryEx(filename, 0, LOAD_LIBRARY_AS_DATAFILE)
    res = _GetResources(hsrc, types, names, languages)
    win32api.FreeLibrary(hsrc)
    return res
Exemple #18
0
def __import(modname):
    import win32api, imp, sys
    suffix = ""
    if win32api.__file__.find("_d") > 0:
        suffix = "_d"
    filename = "%s%d%d%s.dll" % (modname, sys.version_info[0],
                                 sys.version_info[1], suffix)
    # win32 can find the DLL name.
    h = win32api.LoadLibrary(filename)
    found = win32api.GetModuleFileName(h)
    # Python can load the module
    mod = imp.load_module(modname, None, found,
                          ('.dll', 'rb', imp.C_EXTENSION))
    # and fill our namespace with it.
    globals().update(mod.__dict__)
    win32api.FreeLibrary(h)
Exemple #19
0
def hook(mod):
    import sys
    if hasattr(sys, 'version_info'):
        vers = '%d%d' % (sys.version_info[0], sys.version_info[1])
    else:
        import string
        toks = string.split(sys.version[:3], '.')
        vers = '%s%s' % (toks[0], toks[1])
    newname = 'pythoncom%s' % vers
    if mod.typ == 'EXTENSION':
        mod.__name__ = newname
    else:
        import win32api
        h = win32api.LoadLibrary(newname + '.dll')
        pth = win32api.GetModuleFileName(h)
        win32api.FreeLibrary(h)
        import mf
        mod = mf.ExtensionModule(newname, pth)
    return mod
def main():
	# Loading the DLL
	tobii_dll = CDLL("MinimalGazeDataStream.dll")

	identifier = raw_input("ID: ")
	iniTime = str(datetime.datetime.now())

	# Eye-data tracking
	tobii_dll.tobii_start(True) # True: show data-flow in terminal
	waitEnterKey()
	tobii_dll.tobii_stop()

	# Saving eye-data
	file = "gaze" + str(identifier) + ".csv"
	tobii_dll.tobii_save(file)
	cleanCSV(file, iniTime)

	# Releasing the DLL
	win32api.FreeLibrary(tobii_dll._handle)
Exemple #21
0
 def __exit__(self, type, value, traceback):
     win32api.FreeLibrary(self._handle)
Exemple #22
0
    def __call__(self,
                 title="",
                 msg="",
                 payload=None,
                 iconOpt=ICON_EG,
                 sound=True):
        """
        Show a tip balloon in the Windows Event Center.

        title: Bold text to show in the title of the tip.
        msg: Detail text to show in the tip.
        payload: Python data to include with events triggered from this tip.
        iconOpt: an int or a string:
          0 = No icon
          1 = Info icon
          2 = Warning icon
          3 = Error icon
          4 = EventGhost icon
          string = *full path* to an icon file, a semicolon, and the icon number
            (eg: "C:\\Windows\\system32\\shell32.dll;13")
        sound: Whether to play the notification sound.
        """
        if iconOpt is None:
            iconOpt = self.ICON_EG
        title = eg.ParseString(title or "EventGhost")
        msg = eg.ParseString(msg or "This is a notification from EventGhost.")
        if payload and isinstance(payload, basestring):
            payload = eg.ParseString(payload)

        # https://stackoverflow.com/a/17262942/6692652
        # Create the window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        hwnd = win32gui.CreateWindow(self.plugin.classAtom, "TaskBar", style,
                                     0, 0, win32con.CW_USEDEFAULT,
                                     win32con.CW_USEDEFAULT, 0, 0,
                                     self.plugin.hinst, None)
        win32gui.UpdateWindow(hwnd)
        self.plugin.setPayload(hwnd, payload)

        # Icons management
        # Default to no icon if something goes weird
        hicon = None
        dwInfoFlags = 0x00
        try:
            if iconOpt == self.ICON_INFO:
                dwInfoFlags = NIIF_INFO | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_WARNING:
                dwInfoFlags = NIIF_WARNING | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_ERROR:
                dwInfoFlags = NIIF_ERROR | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_EG:
                # Get the first icon from the EventGhost executable
                hicon = win32gui.CreateIconFromResource(
                    win32api.LoadResource(None, win32con.RT_ICON, 1), True)
                dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON
            elif isinstance(iconOpt, basestring):
                filename, idx = iconOpt.split(";", 1)
                filename = expandvars(filename)
                dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON
                if filename[-4:].upper() == ".ICO":
                    hicon = win32gui.LoadImage(
                        win32api.GetModuleHandle(None),
                        filename,
                        win32con.IMAGE_ICON,
                        0,
                        0,
                        win32con.LR_LOADFROMFILE | win32con.LR_LOADREALSIZE,
                    )
                else:
                    lib = win32api.LoadLibrary(filename)
                    hicon = win32gui.LoadIcon(lib, int(idx) + 1)
                    win32api.FreeLibrary(lib)
        except Exception as ex:
            eg.PrintError(str(ex))
            hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
            dwInfoFlags = 0x00
        if not sound:
            dwInfoFlags |= NIIF_NOSOUND
        flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
        nid = (hwnd, 0, flags, WM_TRAYICON, hicon, 'Tooltip')

        # Notify
        win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)
        win32gui.Shell_NotifyIcon(
            win32gui.NIM_MODIFY,
            (hwnd, 0, win32gui.NIF_INFO, WM_TRAYICON, hicon, 'Balloon Tooltip',
             msg, 200, title, dwInfoFlags))
        if hicon is not None:
            win32gui.DestroyIcon(hicon)
Exemple #23
0
 def __del__(self):
     global system
     if system == "Windows":
         import win32api
         win32api.FreeLibrary(self.dllhandle)
Exemple #24
0
###
### A wrapper for the libusb wrapper of the libusb library :-)
###
### This code is in the Public Domain.  (libusb and the wrapper
### are LGPL)
###

from __future__ import generators

import sys

if sys.platform == 'win32':
    try:
        import win32api
        handle = win32api.LoadLibrary("libusb0.dll")
        win32api.FreeLibrary(handle)
    except:
        raise ImportError(
            "libusb needs to be installed for this module to work")

import libusb as usb

# grab some constants and put them in our namespace

for sym in dir(usb):
    if sym.startswith("USB_CLASS_") or sym.startswith("USB_DT"):
        exec "%s=usb.%s" % (sym, sym)
del sym

TRACE = False
Exemple #25
0
"""A useful wrapper around the "_winxptheme" module.
Unlike _winxptheme, this module will load on any version of Windows.

If _winxptheme is not available, then this module will have only 2 functions -
IsAppThemed() and IsThemeActive, which will both always return False.

If _winxptheme is available, this module will have all methods in that module,
including real implementations of IsAppThemed() and IsThemeActive().
"""

import win32api
try:
    win32api.FreeLibrary(win32api.LoadLibrary("Uxtheme.dll"))
    # Life is good, everything is available.
    from _winxptheme import *
except win32api.error:
    # Probably not running XP.
    def IsAppThemed():
        return False

    def IsThemeActive():
        return False

del win32api
Exemple #26
0
global li
li=[]
cmd=[]

if(len(list1)!=0):
	for n in list1:
		cmd.append((n.strip('\r\n')))   
		addlaunch(n.strip('\r\n'))
		
	
root.resizable(0,0)
root.wm_attributes("-topmost", 1,"-alpha",TRANSPARENT)
myH= int(eval(root.wm_frame()))
root.title('nul')
dock.pack(side=TOP, fill=X)
dock.update()
root.update()
mainloop()


#=============================================================
#eg2:

import win32api
lib_hnd = win32api.LoadLibrary( "user32.dll" )
if lib_hnd:
fn_addr = win32api.GetProcAddress( lib_hnd, "MessageBeep" ) # returns int(2010532466)
if fn_addr:
# Here I'd like to call fn_addr. In C it would be plain fn_addr()
win32api.FreeLibrary( lib_hnd )
Exemple #27
0
 def release_dll(self):
     win32api.FreeLibrary(self.dll_handle._handle)
Exemple #28
0
 def __del__(self):
     self.__stop()
     win32api.FreeLibrary(self.__dll._handle)
Exemple #29
0
    def dispose(self):
        self._table = {}

        if self._winhandle:
            win32api.FreeLibrary(self._winhandle)
            self._winhandle = None
Exemple #30
0
 def shifang(self):
     win32api.FreeLibrary(self.dd_dll._handle)