Re: Acquiring process handle and convert it into PID

eryk sun <[email protected]> Wed, 30 Nov 2016 15:55:28 +0000
Newsgroups gmane.comp.python.ctypes
Message-ID <CACL+1avNZ6KDnyzUF9dzB58LYvdjCNNj3_p6_G_XiPmpFSOSjQ@mail.gmail.com>
On Tue, Nov 29, 2016 at 10:07 PM, Michael C
<[email protected]> wrote:
> I ran this but the value returned was 0. I am trying to save time by
> automating the PID acquisition process.
>
> import ctypes
> import time
>
> time.sleep(2)
> handle = ctypes.windll.user32.GetForegroundWindow()
> print(handle)
> PID = ctypes.windll.kernel32.GetProcessId(handle)
> print (PID)

GetProcessId is the wrong function.

To begin with, before writing a single line of code, you need to
familiarize yourself with the subject of WinAPI handles. Carefully
read the following pages:

Object categories
https://msdn.microsoft.com/en-us/library/ms724515
User
https://msdn.microsoft.com/en-us/library/ms725486
GDI
https://msdn.microsoft.com/en-us/library/ms724291
Kernel
https://msdn.microsoft.com/en-us/library/ms724485

Here's the function you'll need:

GetWindowThreadProcessId
https://msdn.microsoft.com/en-us/library/ms633522

Also, please stop using ctypes.windll. The global library loaders were
an extremely bad idea.

------------------------------------------------------------------------------