Skip to content

Instantly share code, notes, and snippets.

@fairjm
Created February 19, 2016 01:56
Show Gist options
  • Save fairjm/d9caa46a4267369eead2 to your computer and use it in GitHub Desktop.
Save fairjm/d9caa46a4267369eead2 to your computer and use it in GitHub Desktop.
get fore ground window
/// <summary>
/// by fairjm.
/// 2016/02/19
/// </summary>
class Program
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
static void Main(string[] args)
{
var a = new { name = "cc" };
while (true)
{
Thread.Sleep(1000);
IntPtr handler = GetForegroundWindow();
if(handler == null)
{
Console.WriteLine("No Process");
continue;
}
uint pid;
GetWindowThreadProcessId(handler, out pid);
Console.WriteLine($"Current Time:{DateTime.Now.ToString()}");
Console.WriteLine($"Id: {pid}");
var process = Process.GetProcessById((int)pid);
Console.WriteLine($"Process File Name: {process.MainModule.FileName}");
Console.WriteLine($"Process Title: {process.MainWindowTitle}");
Console.WriteLine($"Process Name: {process.ProcessName}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment