Get Processes and Windows using C#

Add a reference in your project to System.Management namespace.

Windows API:

private delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
[DllImport("user32.dll")]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, int lParam);

List Opened Windows:

private static void ListWindows()
{
	try
	{
		Console.WriteLine("Opened Windows");
		Console.WriteLine("*****************\n");
		EnumWindows(delegate(IntPtr hWnd, int param)
		{
			int len = GetWindowTextLength(hWnd);
			if (len++ == 0) return true;
 
			StringBuilder str = new StringBuilder(len);
			GetWindowText(hWnd, str, str.Capacity);
			if (!String.IsNullOrEmpty(str.ToString()))
			{
				Console.WriteLine("ID   :\t" + hWnd.ToInt32().ToString());
				Console.WriteLine("Title:\t" + str.ToString());
				Console.WriteLine();
			}
 
			return true;
		}, 0);
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
}

List running Processes:

private static void ListProcesses()
{
	try
	{
		Console.WriteLine("Running Processes");
		Console.WriteLine("*****************\n");
		foreach (ManagementObject mo in 
                                 new ManagementClass("Win32_Process").GetInstances())
		{
			Console.WriteLine("Process Information");
			Console.WriteLine("ID  :\t" + mo["ProcessId"].ToString());
			Console.WriteLine("Name:\t" + mo["Name"].ToString());
			if (mo["ExecutablePath"] != null)
				Console.WriteLine("File:\t" + 
                                                    mo["ExecutablePath"].ToString());
			Console.WriteLine();
 
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
}
Categories: C# Tags: , , ,
%d bloggers like this: