Beispiel #1
0
def get_process_id(
    window_class: str = None,
    window_title: str = None,
) -> Tuple[int, int]:
    """Gets process ID by finding the window either via
    its class or title.

    Args:
        window_class (str, optional): Window class
        window_title (str, optional): Window title

    Returns:
        Tuple[int, int]: PID, HWND
    """

    try:
        arg1 = LPCSTR(window_class.encode("utf-8"))
    except AttributeError:
        arg1 = None

    try:
        arg2 = LPCSTR(window_title.encode("utf-8"))
    except AttributeError:
        arg2 = None

    hwnd = FindWindow(arg1, arg2)

    pid = DWORD()
    GetWindowThreadProcessId(hwnd, byref(pid))

    return pid.value, hwnd
Beispiel #2
0
def find_window(name):
    """
        Find the window with the given class or "name" (text).

        \returns
            PyWnd for the window.
    """

    if name.startswith(CLASS_NAME):
        name = name[len(CLASS_NAME):]
    if name.startswith(TEXT_NAME):
        name = name[len(TEXT_NAME):]

    w = None

    if user32:
        try:
            w = user32.FindWindowA(LPCSTR(name), 0)
            if w:
                w = a_window(w)
            else:
                w = None
                w = user32.FindWindowA(0, LPCSTR(name))
                if w:
                    w = a_window(w)
                else:
                    w = None
                pass
            pass
        except:
            w = None
        pass

    elif X:
        wa = get_windows()
        for ww in wa:
            if name == ww.get_wm_name():
                w = ww
                break
            pass

        if not w:
            for ww in wa:
                cl = ww.get_wm_class()
                if name in cl:
                    w = ww
                    break
                pass
            pass
        pass

    return (w)
Beispiel #3
0
def _getExpandedCounterPaths(processName, counterName):
  '''
  Get list of expanded counter paths given a counter name. Returns a
  list of strings or None, if no counter paths can be created
  '''
  pcchPathListLength = DWORD(0)
  szWildCardPath = LPSTR('\\process(%s)\\%s' % (processName, counterName))
  if pdh.PdhExpandCounterPathA(szWildCardPath, LPSTR(None),
                                      pointer(pcchPathListLength)) != _PDH_MORE_DATA:
    return None

  pathListLength = pcchPathListLength.value
  szExpandedPathList = LPCSTR('\0' * pathListLength)
  if pdh.PdhExpandCounterPathA(szWildCardPath, szExpandedPathList,
                               pointer(pcchPathListLength)) != 0:
    return None
  buffer = create_string_buffer(pcchPathListLength.value)
  memmove(buffer, szExpandedPathList, pcchPathListLength.value)

  paths = []
  i=0
  path = ''
  for j in range(0, pcchPathListLength.value):
    c = struct.unpack_from('c', buffer, offset=j)[0]
    if c == '\0':
      if j == i:
        # double null: we're done
        break
      paths.append(path)
      path = ''
      i = j + 1
    else:
      path += c

  return paths
Beispiel #4
0
    def __write(self, write_buffer, write_overlap):
        self.__debug('writing pipe')
        result = WriteFile(
            self.__pipe_handle,
            LPCSTR(write_buffer),
            len(write_buffer),
            NULL,
            ctypes.byref(write_overlap)
        )

        err = GetLastError()

        if result:
            self.__debug('data written')
            return False
        if err == ERROR_IO_PENDING:
            self.__debug('data pending write')
            return True
        elif err:
            try:
                raise PipeError(err)
            except PipeError:
                LOGGING.error(traceback.format_exc())
            CloseHandle(write_overlap.hEvent)
            self.reconnect()
            return True
Beispiel #5
0
def main(argv):
	import datetime
	if len(argv)==1:
		from xpra.platform.win32.printing import get_printers
		printers = get_printers()
		log("printers: %s", printers)
		printer_name = printers.keys()[0]
	elif len(argv)==2:
		printer_name = argv[1]
	else:
		log.error("usage: %s [printer-name]", argv[0])
		return 1

	title = "Test Page"
	log.warn("HELLO1")
	x = GDIPrinterContext(printer_name)
	log.warn("HELLO GDIPrinterContext: %s", x)

	with GDIPrinterContext(printer_name) as hdc:
		log("hdc=%s", hdc)
		docinfo = DOCINFO()
		docinfo.lpszDocName = LPCSTR("%s\0" % title)
		log("StartDocA(%#x, %s)", hdc, docinfo)
		r = StartDocA(hdc, pointer(docinfo))
		if r<0:
			log.error("StartDocA failed: %i", r)
			return r
		log("StartDocA()=%i" % r)
		r = StartPage(hdc)
		if r<0:
			log.error("StartPage failed: %i", r)
			return r
		x, y = 100, 100
		s = "Test Page printed at %s" % (datetime.datetime.now())
		if not TextOutA(hdc, x, y, LPCSTR(s), len(s)):
			log.error("TextOutA failed")
			return 1
		r = EndPage(hdc)
		if r<0:
			log.error("EndPage failed: %i", r)
			return r
		r = EndDoc(hdc)
		if r<0:
			log.error("EndDoc failed: %i" % r)
			return r
		log("EndDoc()=%i" % r)
		return 0
Beispiel #6
0
    def _addCounter(self, processName, counterType, counterName):
        pCounterPathElements = _PDH_COUNTER_PATH_ELEMENTS_A(
            LPSTR(None),
            LPSTR(counterType),
            LPSTR(processName),
            LPSTR(None),
            DWORD(-1),
            LPSTR(counterName),
        )

        pcchbufferSize = DWORD(0)

        # First run we just try to get the buffer size so we can allocate a
        # string big enough to fill it
        if (pdh.PdhMakeCounterPathA(
                pointer(pCounterPathElements),
                LPCSTR(0),
                pointer(pcchbufferSize),
                DWORD(0),
        ) != _PDH_MORE_DATA):
            raise TalosError(
                "Could not create counter path for counter %s for %s" %
                (counterName, processName))

        szFullPathBuffer = LPCSTR("\0" * pcchbufferSize.value)
        # Then we run to get the actual value
        if (pdh.PdhMakeCounterPathA(
                pointer(pCounterPathElements),
                szFullPathBuffer,
                pointer(pcchbufferSize),
                DWORD(0),
        ) != 0):
            raise TalosError(
                "Could not create counter path for counter %s for %s" %
                (counterName, processName))

        path = szFullPathBuffer.value

        hq = HANDLE()
        if pdh.PdhOpenQuery(None, None, byref(hq)) != 0:
            raise TalosError("Could not open win32 counter query")

        hc = HANDLE()
        if pdh.PdhAddCounterA(hq, path, 0, byref(hc)) != 0:
            raise TalosError("Could not add win32 counter %s" % path)

        self.registeredCounters[counterName] = [hq, [(hc, path)]]
Beispiel #7
0
 def __init__(self, dict):
     if not dict:
         self._as_parameter_ = None
     else:
         values = ["%s=%s" % (key, value) for (key, value) in dict.items()]
         values.append("")
         self._as_parameter_ = LPCSTR(
             "\0\0".join(values).encode("utf-16le"))
Beispiel #8
0
	def __enter__(self):
		self.handle = HANDLE()
		name = LPCSTR(self.printer_name)
		if not OpenPrinterA(name, pointer(self.handle), None):
			raise Exception("failed to open printer %s" % self.printer_name)
		log("OpenPrinter: handle=%#x", self.handle.value)
		size = DWORD(0)
		GetPrinterA(self.handle, 1, None, 0, pointer(size))
		if size.value==0:
			raise Exception("GetPrinterA PRINTER_INFO_1 failed for '%s'" % self.printer_name)
		log("GetPrinter: PRINTER_INFO_1 size=%#x", size.value)
		self.info1 = msvcrt.malloc(size.value)
		if not GetPrinterA(self.handle, 1, self.info1, size.value, pointer(size)):
			raise Exception("GetPrinterA PRINTER_INFO_1 failed for '%s'", self.printer_name)
		info = cast(self.info1, POINTER(PRINTER_INFO_1))
		log(" flags=%#x" % info[0].Flags)
		log(" name=%#s" % info[0].pName)
		log(" description=%s" % info[0].pDescription)
		log(" comment=%s" % info[0].pComment)

		size = DWORD(0)
		GetPrinterA(self.handle, 2, None, 0, pointer(size))
		if size.value==0:
			raise Exception("GetPrinterA PRINTER_INFO_2 failed for '%s'", self.printer_name)
		log("GetPrinter: PRINTER_INFO_2 size=%#x", size.value)
		self.info2 = msvcrt.malloc(size.value)
		if GetPrinterA(self.handle, 2, self.info2, size.value, pointer(size)):
			info = cast(self.info2, POINTER(PRINTER_INFO_2))
			log(" driver=%#s" % info[0].pDriverName)

		size = DWORD(0)
		GetPrinterA(self.handle, 8, None, 0, pointer(size))
		if size.value==0:
			raise Exception("GetPrinter: PRINTER_INFO_8 failed for '%s'" % self.printer_name)
		self.info8 = msvcrt.malloc(size.value)
		if GetPrinterA(self.handle, 8, self.info8, size.value, pointer(size)):
			info = cast(self.info8, POINTER(PRINTER_INFO_8))
			if info[0] and info[0].pDevMode:
				devmode = cast(info[0].pDevMode, POINTER(DEVMODE))
				log("PRINTER_INFO_8: devmode=%s" % devmode)
				log("PRINTER_INFO_8: device name='%s'" % devmode[0].dmDeviceName)

		size = DWORD(0)
		GetPrinterA(self.handle, 9, None, 0, pointer(size))
		if size.value==0:
			raise Exception("GetPrinter: PRINTER_INFO_9 failed for '%s'" % self.printer_name)
		log("GetPrinter: PRINTER_INFO_9 size=%#x" % size.value)
		self.info9 = msvcrt.malloc(size.value)
		if GetPrinterA(self.handle, 9, self.info9, size.value, pointer(size)):
			info = cast(self.info9, POINTER(PRINTER_INFO_9))
			if info[0] and info[0].pDevMode:
				devmode = cast(info[0].pDevMode, POINTER(DEVMODE))
				log("PRINTER_INFO_9: devmode=%s" % devmode)
				log("PRINTER_INFO_9: device name=%s" % devmode[0].dmDeviceName)
		assert devmode, "failed to query a DEVMODE for %s" % self.printer_name
		self.hdc = CreateDCA(None, name, None, devmode)
		log("CreateDCA(..)=%#x", self.hdc)
		return self.hdc
Beispiel #9
0
def MessageBox(HWND, BODY, TITLE, UINT):

    code = {3:"Abort",
            2:"Cancel",
            11:"Continue",
            5:"Ignore",
            7:"No",
            1:"OK",
            4:"Retry",
            10:"Try Again",
            6:"Yes"}
    
    int = windll.User32.MessageBoxA(
        HWND,
        LPCSTR(BODY),
        LPCSTR(TITLE),
        UINT
        )
    
    return code[int]
Beispiel #10
0
    def lookup_privilege_value(self, lpSystemName, lpName, luidPrivilege):

        # Calling the Windows API Call to
        response = self.__advapi_handler.LookupPrivilegeValueA(
            lpSystemName, LPCSTR(lpName.encode("utf-8")),
            ctypes.byref(luidPrivilege))

        if response <= 0 or response is None:
            PrintScreen.err(
                "lookup_privilege_value: Lookup For {0} Failed".format(lpName))
            self.assert_last_error()
        else:
            PrintScreen.log("Lookup For {0} worked".format(lpName))

        return response
Beispiel #11
0
def open_event(event_name: str,
               desired_access: int = EVENT_ALL_ACCESS,
               inherit_handle: bool = False) -> HANDLE:
    """
    Attempts to open an event object with the given name at the requested access level.

    The name must easily convert to ascii.

    :param event_name: a name to open. must be convertible to ascii
    :param desired_access:
    :param inherit_handle: whether child processes get access to the handle.
    :return: a handle for the event if successful
    """
    return _open_event(DWORD(desired_access), BOOL(inherit_handle),
                       LPCSTR(bytes(event_name, 'ASCII')))
Beispiel #12
0
def _getExpandedCounterPaths(processName, counterName):
    """
    Get list of expanded counter paths given a counter name. Returns a
    list of strings or None, if no counter paths can be created
    """
    pcchPathListLength = DWORD(0)
    szWildCardPath = LPSTR("\\process(%s)\\%s" % (processName, counterName))
    if (pdh.PdhExpandCounterPathA(szWildCardPath, LPSTR(None),
                                  pointer(pcchPathListLength)) !=
            _PDH_MORE_DATA):
        return []

    pathListLength = pcchPathListLength.value
    szExpandedPathList = LPCSTR("\0" * pathListLength)
    if (pdh.PdhExpandCounterPathA(szWildCardPath, szExpandedPathList,
                                  pointer(pcchPathListLength)) != 0):
        return []
    buffer = create_string_buffer(pcchPathListLength.value)
    memmove(buffer, szExpandedPathList, pcchPathListLength.value)

    paths = []
    i = 0
    path = ""
    for j in six.moves.range(0, pcchPathListLength.value):
        c = struct.unpack_from("c", buffer, offset=j)[0]
        if c == "\0":
            if j == i:
                # double null: we're done
                break
            paths.append(path)
            path = ""
            i = j + 1
        else:
            path += c

    return paths
Beispiel #13
0
avi.AVIFileCreateStreamA.argtypes = [c_int, POINTER(c_void_p), POINTER(AVISTREAMINFOA)]
avi.AVIFileCreateStreamA.restype = c_int

avi.AVISaveOptions.argtypes = [HWND, UINT, c_int, POINTER(c_void_p), c_void_p]
avi.AVISaveOptions.restype = c_int

avi.AVIFileRelease.argtypes = [c_int]
avi.AVIFileRelease.restype = c_int

avi.AVIStreamRelease.argtypes = [c_void_p]
avi.AVIStreamRelease.restype = c_int

if __name__ == "__main__":
    avifile = c_int(0)
    avi.AVIFileInit()
    avi.AVIFileOpenA(pointer(avifile), LPCSTR("__tmp__.avi"), OF_WRITE|OF_CREATE, 0)

    aviinfo = AVISTREAMINFOA()
    aviinfo.fccType = fourcc("vids")

    stream = c_void_p(0)
    avi.AVIFileCreateStreamA(avifile, pointer(stream), pointer(aviinfo))

    opt = AVICOMPRESSOPTIONS()
    popt = ctypes.pointer(opt)
    opt.fccType = fourcc("vids")
    avi.AVISaveOptions(0, 0, 1, pointer(stream), pointer(ctypes.pointer(opt)))
    print((unfourcc(opt.fccHandler)))
    
    avi.AVIStreamRelease(stream)
    avi.AVIFileRelease(avifile)
Beispiel #14
0
    def priority(level=0, pid=None):
        # 0 = normal priority
        # 1 = high
        # 2 = realtime
        gc.disable() if level > 0 else gc.enable()

        if kernel32 is None and avrt is None:
            # nothing to do if we don't have these
            return False

        pid = os.getpid()
        process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION, 0, pid)
        thread = kernel32.GetCurrentThread()

        if thread in thread_pool.keys():
            thread_grp = thread_pool[thread]
        else:
            thread_grp = {'mmcss': None}
            thread_pool[thread] = thread_grp

        # if this is a MMCSS scheduled thread, need to revert to normal first
        if avrt and thread_grp['mmcss']:
            avrt.AvRevertMmThreadCharacteristics(thread_grp['mmcss'])
            thread_grp['mmcss'] = None

        # clear error if anything?
        err = get_last_error()
        if err:
            set_last_error(0)
            return False

        if level == 1:
            kernel32.SetPriorityClass(process, HIGH_PRIORITY_CLASS)
            if avrt:
                tmp = LPDWORD()
                thread_grp['mmcss'] = avrt.AvSetMmMaxThreadCharacteristicsA(LPCSTR(b'Pro Audio'),
                                                                            LPCSTR(b'Capture'),
                                                                            byref(tmp))
            if not thread_grp['mmcss']:  # failed
                kernel32.SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST)

        elif level >= 2:
            # first try to set time critical
            if (not kernel32.SetPriorityClass(process, REALTIME_PRIORITY_CLASS) or
                    kernel32.GetPriorityClass(process) != REALTIME_PRIORITY_CLASS):
                # try for high priority scheduling instead
                kernel32.SetPriorityClass(process, HIGH_PRIORITY_CLASS)
            if avrt:
                tmp = LPDWORD()
                thread_grp['mmcss'] = avrt.AvSetMmMaxThreadCharacteristicsA(LPCSTR(b'Pro Audio'),
                                                                            LPCSTR(b'Capture'),
                                                                            byref(tmp))
            if not thread_grp['mmcss']:  # failed
                kernel32.SetThreadPriority(
                    thread, THREAD_PRIORITY_ABOVE_NORMAL)

        else:
            kernel32.SetPriorityClass(process, NORMAL_PRIORITY_CLASS)
            kernel32.SetThreadPriority(thread, THREAD_PRIORITY_NORMAL)

        return True
Beispiel #15
0
]
avi.AVIFileCreateStreamA.restype = c_int

avi.AVISaveOptions.argtypes = [HWND, UINT, c_int, POINTER(c_void_p), c_void_p]
avi.AVISaveOptions.restype = c_int

avi.AVIFileRelease.argtypes = [c_int]
avi.AVIFileRelease.restype = c_int

avi.AVIStreamRelease.argtypes = [c_void_p]
avi.AVIStreamRelease.restype = c_int

if __name__ == "__main__":
    avifile = c_int(0)
    avi.AVIFileInit()
    avi.AVIFileOpenA(pointer(avifile), LPCSTR("__tmp__.avi"),
                     OF_WRITE | OF_CREATE, 0)

    aviinfo = AVISTREAMINFOA()
    aviinfo.fccType = fourcc("vids")

    stream = c_void_p(0)
    avi.AVIFileCreateStreamA(avifile, pointer(stream), pointer(aviinfo))

    opt = AVICOMPRESSOPTIONS()
    popt = ctypes.pointer(opt)
    opt.fccType = fourcc("vids")
    avi.AVISaveOptions(0, 0, 1, pointer(stream), pointer(ctypes.pointer(opt)))
    print unfourcc(opt.fccHandler)

    avi.AVIStreamRelease(stream)
Beispiel #16
0
import ctypes
from ctypes.wintypes import LPCSTR, UINT
import os

a1800dll = ctypes.WinDLL('a1800.dll')

# enc doesn't seem to work - need to double-check the parms
encproto = ctypes.WINFUNCTYPE(ctypes.c_uint, LPCSTR, LPCSTR, UINT, ctypes.POINTER(UINT), UINT)
encparamflags = ((1, 'infile'), (1, 'outfile'), (1, 'samprate', 16001), (2, 'fh'), (1,'unk', 0))
encfunc = encproto(('enc', a1800dll), encparamflags)

decproto = ctypes.WINFUNCTYPE(ctypes.c_uint, LPCSTR, LPCSTR, ctypes.POINTER(UINT), UINT, UINT)
decparamflags = ((1, 'infile'), (1, 'outfile'), (2, 'fp'), (1, 'unk1', 16000), (1,'unk2', 0))
decfunc = decproto(('dec', a1800dll), decparamflags)

#ret=encfunc(infile=LPCSTR('cow1.wav'.encode('ascii')), outfile=LPCSTR('out.a18'.encode('ascii')))
#print(ret)
#ret=decfunc(infile=LPCSTR('tu003410_4701Ah_115Eh.a18'.encode('ascii')), outfile=LPCSTR('out.wav'.encode('ascii')))
#print(ret)

files=os.listdir('3410') # directory with the a18 files extracted from the DLC
for f in files:
    fname = '3410/' + f
    outfile = 'wavs/' + f + '.wav' # directy to output to
    print(fname)
    decfunc(infile=LPCSTR(fname.encode('ascii')), outfile=LPCSTR(outfile.encode('ascii')))


Beispiel #17
0
 def __new__(cls, obj):
     return LPCSTR.__new__(cls, obj.encode("mbcs"))
Beispiel #18
0
def send_single_message(pipe_name, msg, packet_size=DEFAULT_PACKET_SIZE):
    pipe_name = _create_pipe_name(pipe_name)
    while True:
        pipe_handle = CreateFile(
            pipe_name,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL
        )
        if pipe_handle != INVALID_HANDLE_VALUE:
            break
        if GetLastError() != ERROR_PIPE_BUSY:
            pass
        elif WaitNamedPipe(pipe_name, 2000) == 0:
            CloseHandle(pipe_handle)
            return False

    pipe_mode = ULONG(PIPE_READMODE_MESSAGE)
    result = SetNamedPipeHandleState(
        pipe_handle,
        ctypes.byref(pipe_mode),
        NULL,
        NULL
    )

    if not result:
        err = GetLastError()
        CloseHandle(pipe_handle)
        if err:
            raise PipeError(err)
        else:
            raise PipeError(
                'send_single_message SetNamedPipeHandleState failed'
            )

    write_bytes = ULONG(0)

    while len(msg) != write_bytes.value:

        result = WriteFile(
            pipe_handle,
            LPCSTR(msg),
            len(msg),
            ctypes.byref(write_bytes),
            None
        )
        if not result:
            err = GetLastError()

            if err != ERROR_MORE_DATA:
                CloseHandle(pipe_handle)
                raise PipeError(err)

    result = 0
    read_buffer = ctypes.create_string_buffer(packet_size)
    read_bytes = ULONG(0)

    while not result:  # repeat loop if ERROR_MORE_DATA
        result = ReadFile(
            pipe_handle,
            read_buffer,
            packet_size,
            ctypes.byref(read_bytes),
            NULL
        )

        err = GetLastError()
        if err != ERROR_MORE_DATA:
            break

    CloseHandle(pipe_handle)
    return read_buffer.value
Beispiel #19
0
 def __new__(cls, obj):
     return LPCSTR.__new__(cls, obj.encode("mbcs"))