Python win32process.GetWindowThreadProcessId() Examples

The following are 18 code examples of win32process.GetWindowThreadProcessId(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32process , or try the search function .
Example #1
Source File: windows.py    From ATX with Apache License 2.0 6 votes vote down vote up
def __init__(self, window_name=None, exe_file=None, exclude_border=True):
        hwnd = 0

        # first check window_name
        if window_name is not None:
            hwnd = win32gui.FindWindow(None, window_name)
            if hwnd == 0:
                def callback(h, extra):
                    if window_name in win32gui.GetWindowText(h):
                        extra.append(h)
                    return True
                extra = []
                win32gui.EnumWindows(callback, extra)
                if extra: hwnd = extra[0]
            if hwnd == 0:
                raise WindowsAppNotFoundError("Windows Application <%s> not found!" % window_name)

        # check exe_file by checking all processes current running.
        elif exe_file is not None:
            pid = find_process_id(exe_file)
            if pid is not None:
                def callback(h, extra):
                    if win32gui.IsWindowVisible(h) and win32gui.IsWindowEnabled(h):
                        _, p = win32process.GetWindowThreadProcessId(h)
                        if p == pid:
                            extra.append(h)
                        return True
                    return True
                extra = []
                win32gui.EnumWindows(callback, extra)
                #TODO: get main window from all windows.
                if extra: hwnd = extra[0]
            if hwnd == 0:
                raise WindowsAppNotFoundError("Windows Application <%s> is not running!" % exe_file)

        # if window_name & exe_file both are None, use the screen.
        if hwnd == 0:
            hwnd = win32gui.GetDesktopWindow()

        self.hwnd = hwnd
        self.exclude_border = exclude_border 
Example #2
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def PyGetWindowThreadProcessId(hWnd):
    """
    Retrieves the identifier of the thread and process that created the
    specified window.

    int threadId, int processId = GetWindowThreadProcessId(hWnd)
    """
    dwProcessId = DWORD()
    threadId = GetWindowThreadProcessId(hWnd, byref(dwProcessId))
    return threadId, dwProcessId.value 
Example #3
Source File: winprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __close__(self, hwnd, dummy):
        """
        EnumWindows callback - sends WM_CLOSE to any window
        owned by this process.
        """
        TId, PId = win32process.GetWindowThreadProcessId(hwnd)
        if PId == self.PId:
            win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) 
Example #4
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def GetWindowProcessName(hWnd):
    dwProcessId = DWORD()
    GetWindowThreadProcessId(hWnd, byref(dwProcessId))
    return GetProcessName(dwProcessId.value) 
Example #5
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def GetHwnds(pid = None, processName = None):
    if pid:
        pass
    elif processName:
        pids = GetPids(processName = processName)
        if pids:
            pid = pids[0]
        else:
            return False
    else:
        return False

    def callback(hwnd, hwnds):
        if IsWindowVisible(hwnd):
            _, result = GetWindowThreadProcessId(hwnd)
            if result == pid:
                hwnds.append(hwnd)
        return True

    from win32gui import EnumWindows, IsWindowVisible
    from win32process import GetWindowThreadProcessId
    hwnds = []
    EnumWindows(callback, hwnds)
    return hwnds 
Example #6
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def BringHwndToFront(hWnd, invalidate=True):
    if hWnd is None:
        return
    hWnd = GetAncestor(hWnd, GA_ROOT)
    if not IsWindow(hWnd):
        return

    # If the window is in a minimized state, restore now
    if IsIconic(hWnd):
        ShowWindow(hWnd, SW_RESTORE)
        BringWindowToTop(hWnd)
        UpdateWindow(hWnd)

    # Check to see if we are the foreground thread
    foregroundHwnd = GetForegroundWindow()
    foregroundThreadID = GetWindowThreadProcessId(foregroundHwnd, None)
    ourThreadID = GetCurrentThreadId()

    # If not, attach our thread's 'input' to the foreground thread's
    if foregroundThreadID != ourThreadID:
        AttachThreadInput(foregroundThreadID, ourThreadID, True)

    ShowWindow(hWnd, SW_SHOWNA)
    BringWindowToTop(hWnd)
    # Force our window to redraw
    if invalidate:
        InvalidateRect(hWnd, None, True)
    if foregroundThreadID != ourThreadID:
        AttachThreadInput(foregroundThreadID, ourThreadID, False) 
Example #7
Source File: logwriter.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def GetProcessNameFromHwnd(self, hwnd):
		'''Acquire the process name from the window handle for use in the log filename.
		'''
		threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd)
		
		# PROCESS_QUERY_INFORMATION (0x0400) or PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF)
		
		mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid)
		procname = win32process.GetModuleFileNameEx(mypyproc, 0)
		return procname 
Example #8
Source File: Demo_Save_Windows_As_Images.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_window_list():
    titles = []
    t = []
    pidList = [(p.pid, p.name()) for p in psutil.process_iter()]

    def enumWindowsProc(hwnd, lParam):
        """ append window titles which match a pid """
        if (lParam is None) or ((lParam is not None) and (win32process.GetWindowThreadProcessId(hwnd)[1] == lParam)):
            text = win32gui.GetWindowText(hwnd)
            if text:
                wStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
                if wStyle & win32con.WS_VISIBLE:
                    t.append("%s" % (text))
                    return

    def enumProcWnds(pid=None):
        win32gui.EnumWindows(enumWindowsProc, pid)

    for pid, pName in pidList:
        enumProcWnds(pid)
        if t:
            for title in t:
                titles.append("('{0}', '{1}')".format(pName, title))
            t = []
    titles = sorted(titles, key=lambda x: x[0].lower())
    return titles 
Example #9
Source File: super_hexagon_bot.py    From Super-Hexagon-Bot with The Unlicense 5 votes vote down vote up
def main():
    # Find Super Hexagon process id by searching window names
    window_handle = win32ui.FindWindow(None, u"Super Hexagon").GetSafeHwnd()
    pid = win32process.GetWindowThreadProcessId(window_handle)[1]

    memory = Memory(pid)
    hexagon = SuperHexagon(memory)
    logic = Logic(hexagon)
    logic.start()
    memory.close_handle() 
Example #10
Source File: main.py    From MouseTracks with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent=True, console=False):
        """Get the handle of the currently focused window."""
        self.hwnd = get_window_handle(parent, console)
        self.pid = win32process.GetWindowThreadProcessId(self.hwnd)[1] 
Example #11
Source File: tcp.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def enumCallback(hwnd, windowName):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            try:

                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    return

                (threadId, processId) = win32process.GetWindowThreadProcessId(hwnd)

                # Send WM_CLOSE message
                try:
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    win32gui.PostQuitMessage(hwnd)
                except:
                    pass

                # Give it upto 5 sec
                for i in range(100):
                    if win32process.GetExitCodeProcess(processId) != win32con.STILL_ACTIVE:
                        # Process exited already
                        return

                    time.sleep(0.25)

                try:
                    # Kill application
                    win32process.TerminateProcess(processId, 0)
                except:
                    pass
            except:
                pass 
Example #12
Source File: main.py    From PUBG with The Unlicense 5 votes vote down vote up
def activeWindowName():
	hwnd = win32gui.GetForegroundWindow()
	tid, current_pid = win32process.GetWindowThreadProcessId(hwnd)
	return psutil.Process(current_pid).name() 
Example #13
Source File: windows.py    From aw-watcher-window with Mozilla Public License 2.0 5 votes vote down vote up
def get_app_name(hwnd) -> Optional[str]:
    """Get application filename given hwnd."""
    name = None
    _, pid = win32process.GetWindowThreadProcessId(hwnd)
    for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
        name = p.Name
        break
    return name 
Example #14
Source File: winpty.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def get_hwnds_for_pid(pid):
    def callback(hwnd, hwnds):
        # if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
        # print hwnd
        if found_pid == pid:
            hwnds.append(hwnd)
        return True
    hwnds = []
    win32gui.EnumWindows(callback, hwnds)
    return hwnds 
Example #15
Source File: _win32.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_current_layout(cls):
        # Get the current window's keyboard layout.
        thread_id = win32process.GetWindowThreadProcessId(
            win32gui.GetForegroundWindow()
        )[0]
        return win32api.GetKeyboardLayout(thread_id) 
Example #16
Source File: main.py    From PUBG with The Unlicense 4 votes vote down vote up
def enum_window_callback(hwnd, pid):
    tid, current_pid = win32process.GetWindowThreadProcessId(hwnd)
    if pid == current_pid and win32gui.IsWindowVisible(hwnd):
        win32gui.SetForegroundWindow(hwnd)
        l("window activated") 
Example #17
Source File: windows.py    From airtest with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _getHandleThroughFilename(self):
        Psapi = ctypes.WinDLL('Psapi.dll')
        EnumProcesses = Psapi.EnumProcesses
        EnumProcesses.restype = ctypes.wintypes.BOOL
        GetProcessImageFileName = Psapi.GetProcessImageFileNameA
        GetProcessImageFileName.restype = ctypes.wintypes.DWORD

        Kernel32 = ctypes.WinDLL('kernel32.dll')
        OpenProcess = Kernel32.OpenProcess
        OpenProcess.restype = ctypes.wintypes.HANDLE
        TerminateProcess = Kernel32.TerminateProcess
        TerminateProcess.restype = ctypes.wintypes.BOOL
        CloseHandle = Kernel32.CloseHandle
        

        MAX_PATH = 260
        PROCESS_TERMINATE = 0x0001
        PROCESS_QUERY_INFORMATION = 0x0400

        count = 32
        while True:
            ProcessIds = (ctypes.wintypes.DWORD*count)()
            cb = ctypes.sizeof(ProcessIds)
            BytesReturned = ctypes.wintypes.DWORD()
            if EnumProcesses(ctypes.byref(ProcessIds), cb, ctypes.byref(BytesReturned)):
                if BytesReturned.value<cb:
                    break
                else:
                    count *= 2
            else:
                raise Exception('Call to EnumProcesses failed')

        for index in range(BytesReturned.value / ctypes.sizeof(ctypes.wintypes.DWORD)):
            ProcessId = ProcessIds[index]
            hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, ProcessId)
            if hProcess:
                ImageFileName = (ctypes.c_char*MAX_PATH)()
                if GetProcessImageFileName(hProcess, ImageFileName, MAX_PATH)>0:
                    filename = os.path.basename(ImageFileName.value)
                    if filename == self.filename:
                        break
                #TerminateProcess(hProcess, 1)
                CloseHandle(hProcess)
                
        def get_hwnds_for_pid(pid):
            def callback (hwnd, hwnds):
                if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd):
                    _, found_pid = win32process.GetWindowThreadProcessId (hwnd)
                    if found_pid == pid:
                        hwnds.append (hwnd)
                    return True
            hwnds = []
            win32gui.EnumWindows(callback, hwnds)
            return hwnds
        return get_hwnds_for_pid(ProcessId) 
Example #18
Source File: windows.py    From aw-watcher-window with Mozilla Public License 2.0 4 votes vote down vote up
def get_app_path(hwnd) -> Optional[str]:
    """Get application path given hwnd."""
    path = None
    _, pid = win32process.GetWindowThreadProcessId(hwnd)
    for p in c.query('SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
        path = p.ExecutablePath
        break
    return path