Created
October 24, 2017 21:23
-
-
Save sparksbat/38d3a8c31f36d18cc497831631691067 to your computer and use it in GitHub Desktop.
C# Get Foreground Process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using System.Diagnostics; | |
namespace FGWindow | |
{ | |
class ProcessUtils | |
{ | |
[DllImport("user32.dll")] | |
private static extern IntPtr GetForegroundWindow(); | |
[DllImport("user32.dll", SetLastError = true)] | |
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); | |
public static Process getForegroundProcess() | |
{ | |
uint processID = 0; | |
IntPtr hWnd = GetForegroundWindow(); // Get foreground window handle | |
uint threadID = GetWindowThreadProcessId(hWnd, out processID); // Get PID from window handle | |
Process fgProc = Process.GetProcessById(Convert.ToInt32(processID)); // Get it as a C# obj. | |
// NOTE: In some rare cases ProcessID will be NULL. Handle this how you want. | |
return fgProc; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Threading; | |
namespace FGWindow | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
while (true) | |
{ | |
// This is how you call the GetFGProcess stuff. | |
Process fgProc = ProcessUtils.getForegroundProcess(); | |
Console.WriteLine(fgProc.ProcessName); | |
Thread.Sleep(5000); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works like charm.. Thank you so much!