namespace WindowMonitor
{
using System;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
///
/// Utility class to monitor the currently active window.
///
public class WindowMonitor
{
///
/// Gets a pointer to the currently active window.
///
///
/// A pointer to the active window.
///
public IntPtr GetActiveWindowHandle()
{
return GetForegroundWindow();
}
///
/// Gets the title of the window with the given handle.
///
///
/// The handle of the window to look up.
///
///
/// The textual title of the given window.
///
public string GetWindowTitle(IntPtr handle)
{
var length = GetWindowTextLength(handle);
var buffer = new StringBuilder(length + 1);
GetWindowText(handle, buffer, length + 1);
return buffer.ToString();
}
///
/// Gets the full command line of the process that owns the window
/// with the given handle.
///
///
/// The handle of the window to look up.
///
///
/// The command line of the owning process, or string.Empty if
/// it couldn't be found.
///
public string GetWindowFileName(IntPtr handle)
{
int processId;
GetWindowThreadProcessId(handle, out processId);
if (processId == 0)
{
return string.Empty;
}
var wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId={0}", processId);
var searcher = new ManagementObjectSearcher(wmiQuery);
var resultEnumerator = searcher.Get().GetEnumerator();
return resultEnumerator.MoveNext() ? resultEnumerator.Current["CommandLine"].ToString() : string.Empty;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr handle);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr handle, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
}
}