Finding Windows and their executable filepaths

Search This thread


Senior Member
Dec 21, 2007
I've just spent a lot of time looking for ways to tie Windows and process exe files together and I saw a lot of people asking after similar topics.

It was somewhat frustrating because of numerous little difficulties - using CreateToolhelp32Snapshot unpredictably fails, GetProcessById is no good if the process wasn't started with StartInfo, because you can have multiple windows to a process it's hard to identify which is a processes mainwindow.

But I solved my problem, a solution that I haven't seen elsewhere, so I thought I'd share it here. This is my solution to the specific problem of finding a window to match an executable file path....

This is on WM6, using CF2 in C#.

Used as follows (with S2U2 as the example):

Ionwerks.Window w = new Ionwerks.Window(@"\Program Files\S2U2\S2U2.exe");

IntPtr WindowsHandle = w.handle;

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

namespace Ionwerks
	delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

	class Window
		private EnumWindowsProc callbackDelegate;
		private IntPtr callbackDelegatePointer;

		private IntPtr m_handle = IntPtr.Zero;
		private string moduleFileName = "";

		//Construct from path
		public Window(string path)
			moduleFileName = path;

		public IntPtr handle
				return m_handle;

		private void Enumerate() {
			callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
			callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);

			EnumWindows(callbackDelegatePointer, 0);

		[DllImport("coredll.dll", SetLastError = true)]
		private static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);

		[DllImport("coredll.dll", EntryPoint = "GetModuleFileNameW", SetLastError = true)]
		private static extern uint GetModuleFileName(IntPtr hModule, [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, uint nSize);

		private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out int lpdwProcessId);

		private static extern IntPtr OpenProcess(int flags, bool fInherit, int PID);

		private static extern bool CloseHandle(IntPtr handle);

		private static extern bool IsWindowVisible(IntPtr handle);

		private string ModuleFileName = new string((char)0x20, 255);

		private int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
			//get windows process
			int pid = 0;
			GetWindowThreadProcessId(hwnd, out pid);
			IntPtr pHnd = OpenProcess(0, false, pid);

			//get processes image
			GetModuleFileName(pHnd, ModuleFileName, (uint)ModuleFileName.Length);

			//if paths match up
			if (String.Compare(ModuleFileName.Substring(0, ModuleFileName.IndexOf('\0')), moduleFileName, true) == 0)			{
				//only interested in processes mainwindow
				if (hwnd == Process.GetProcessById(pid).MainWindowHandle)
					m_handle = hwnd;
			return 1;
Last edited: