一段捕捉桌面活动窗体的标题及其进程的代码。主要利用了API及Process类。
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Reflection;

public class GetActiveWin

{

Win32 API#region Win32 API
[DllImport("User32.Dll")]
public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);
[DllImport("User32.Dll")]
public static extern void GetWindowWord(int hWnd, int nIndex);


[DllImport("User32.Dll")]
public static extern void GetClassName(int h, StringBuilder s, int nMaxCount);
[DllImport("User32.Dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern IntPtr GetActiveWindow ();
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private extern static int GetWindowThreadProcessId(int hWnd, ref int lpdwProcessId);

#endregion


全局变量#region 全局变量

private static bool _isWinNT = (Environment.OSVersion.Platform == PlatformID.Win32NT);

#endregion


方法#region 方法
public GetActiveWin()

{
sb=new StringBuilder(1024);
sbc=new StringBuilder(256);
}

private StringBuilder sb;
private StringBuilder sbc;
public IntPtr GetWinHwnd()

{
return GetForegroundWindow();//得到活动窗体的句柄
}


/**//// <summary>
/// 得到窗体的Caption
/// </summary>
/// <returns></returns>
public string GetWinText(IntPtr handl)

{
GetWindowText((int)handl, sb, sb.Capacity); //得到活动窗体的标题
return sb.ToString();
}



/**//// <summary>
/// 得到应用程序类
/// </summary>
/// <returns></returns>
public string GetWinClass(IntPtr handl)

{
GetClassName((int)handl,sbc,sbc.Capacity);
return sbc.ToString();
}


/**//// <summary>
/// 得到运行程序进程名
/// </summary>
/// <param name="handl">句柄</param>
/// <returns></returns>
public string GetProcessName(IntPtr handl)

{
int i=0;
GetWindowThreadProcessId( (int) handl, ref i);
Process proc=Process.GetProcessById(i);
return proc.ProcessName;
}


/**//// <summary>
/// 得到运行程序的路径
/// </summary>
/// <param name="handl"></param>
/// <returns></returns>
public string GetProcessPath(IntPtr handl)

{
int i=0;
GetWindowThreadProcessId( (int) handl, ref i);
Process proc=Process.GetProcessById(i);
return proc.MainModule.FileName;
}


/**//// <summary>
/// 得到进程
/// </summary>
/// <param name="handl"></param>
/// <returns></returns>
public Process GetProcess(IntPtr handl)

{
int i=0;
GetWindowThreadProcessId( (int) handl, ref i);
Process proc=Process.GetProcessById(i);
return proc;
}

#endregion

}
可以用来:1、利用API GetForegroundWindow 获得句柄,捕捉当前活动窗体的名字;
2、并根据活动窗体的句柄, 得到该窗体的使用进程;
3、根据进程,利用System..Diagnostics.Process,得到进程名,及其路径。