Mark S. Rasmussen improve.dk
Apr 03
2007

So we have a handle, what process does it belong to? Our goal is to obtain a .NET System.Diagnostics.Process object that corresponds to the owner process of the handle we input.

Let’s first open up an Internet Explorer window, just leave it at the start page, whatever yours is.

Now fire up Winspector and locate the Internet Explorer window, you’ll see the handle in HEX format in the treeview.

using System;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;

namespace Get_process_from_handle
{
	class Program
	{
		// The DllImport attribute specifies the Win32 DLL that contains the function we're importing,
		// in this case it's the user32.dll file that resides in the C:WindowsSystem32 directory.
		// The function we're importing is GetWindowThreadProcessId, it takes a handle and a reference
		// to an outgoing integer that'll return the process ID of the handle.
		[DllImport("user32")]
		public static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);

		static void Main(string[] args)
		{
			// First, read the handle from the console, remember this has to be in HEX format!
			int handle = int.Parse(Console.ReadLine(), NumberStyles.HexNumber);

			// Now that we have the handle, create an uninitialized integer that'll hold the process ID
			// of the handle process.
			int processID;
			GetWindowThreadProcessId(handle, out processID);

			// Now that we have the process ID, we can use the built in .NET function to obtain a process object.
			Process p = Process.GetProcessById(processID);

			// Finally we'll write out the process name to confirm success.
			Console.Write(p.ProcessName);
			Console.Read();
		}
	}
}

And the result:

Mark S. Rasmussen
I'm the CTO at iPaper where I cuddle with databases, mold code and maintain the overall technical & team responsibility. I'm an avid speaker at user groups & conferences. I love life, motorcycles, photography and all things technical. Say hi on Twitter, write me an email or look me up on LinkedIn.