How to get active process name in C#?
I know that I must use this code:
[DllImport(\"user32.dll\")]
private static extern IntPtr GetForegroundWindow(
Here's a link describing the exact thing you want to do:
http://www.blackwasp.co.uk/GetActiveProcess.aspx
And another one describing the GetForegroundWindow function, which I copy below.
Note that you may need to reference some extra assemblies, for this code to work. Look at the MSDN for each function. Example, GetProcessesByName requires System.Diagnostics.
public ApplicationState AppState
{
get
{
Process[] processCollection =
Process.GetProcessesByName(ProcessName);
if(processCollection != null &&
processCollection.Length >= 1 &&
processCollection[0] != null)
{
IntPtr activeWindowHandle = Win32.GetForegroundWindow();
// Optional int ProcessID;
// Optional Win32.GetWindowThreadProcessId(
GetForegroundWindow(),
out ProcessID)
foreach(Process wordProcess in processCollection)
{
//Optional if( ProcessID == wordProcess.Id )
// return ApplicationState.Focused;
if(wordProcess.MainWindowHandle == activeWindowHandle)
{
return ApplicationState.Focused;
}
}
return ApplicationState.Running;
}
return ApplicationState.NotRunning;
}
}