C#: Detecting which application has focus
Take a look at Application.AddMessageFilter
, and look for WM_ACTIVATEAPP messages, which will tell you when an app is activated, i.e. receives focus.
How can i get application name which is currently focused
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
public string GetActiveWindowTitle()
{
var handle = GetForegroundWindow();
string fileName = "";
string name = "";
uint pid = 0;
GetWindowThreadProcessId(handle, out pid);
Process p = Process.GetProcessById((int)pid);
var processname = p.ProcessName;
switch (processname)
{
case "explorer": //metro processes
case "WWAHost":
name = GetTitle(handle);
return name;
default:
break;
}
string wmiQuery = string.Format("SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId LIKE '{0}'", pid.ToString());
var pro = new ManagementObjectSearcher(wmiQuery).Get().Cast<ManagementObject>().FirstOrDefault();
fileName = (string)pro["ExecutablePath"];
// Get the file version
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
// Get the file description
name = myFileVersionInfo.FileDescription;
if (name == "")
name = GetTitle(handle);
return name;
}
public string GetTitle(IntPtr handle)
{
string windowText = "";
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(handle, Buff, nChars) > 0)
{
windowText = Buff.ToString();
}
return windowText;
}
Determine if current application is activated (has focus)
This works:
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
It has the advantage of being thread-safe, not requiring the main form (or its handle) and is not WPF or WinForms specific. It will work with child windows (even independent ones created on a separate thread). Also, there's zero setup required.
The disadvantage is that it uses a little P/Invoke, but I can live with that :-)
Detect when none of app windows is active/focused
Form
has a ContainsFocus
property that indicates whether the form, or one of its child controls has the input focus. You can check this property for all open forms to detect if the application contains focus or not:
var isActive = Application.OpenForms.Cast<Form>().Any(x=>x.ContainsFocus);
Also as another option:
var isActive = (Form.ActiveForm != null)
If you want to be notified of the state of the application you can handle Activate
and Deactivate
event of your forms for all forms.
private void f_Deactivate(object sender, EventArgs e)
{
BeginInvoke(new Action(() =>
{
if (Form.ActiveForm == null)
Text = "App Deactivated.";
else
Text = "Still Active";
}));
}
How to determine whether my application is active (has focus)
Used P/Invoke and loop
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
private static bool IsActive(Window wnd)
{
// workaround for minimization bug
// Managed .IsActive may return wrong value
if (wnd == null) return false;
return GetForegroundWindow() == new WindowInteropHelper(wnd).Handle;
}
public static bool IsApplicationActive()
{
foreach (var wnd in Application.Current.Windows.OfType<Window>())
if (IsActive(wnd)) return true;
return false;
}
Determine if document ACTUALLY has focus
It is possible only using WinAPI.
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
bool WordHasFocus {
get {
IntPtr wordHandle = Process.GetCurrentProcess().MainWindowHandle;
IntPtr focusedWindow = GetForegroundWindow() ;
return wordHandle == focusedWindow;
}
}
It shows you only that word has focus. If you want to check about given document, you additionally need to ensure that given document is active document.
Check if Form has focus or is active
if (Form.ActiveForm != yourform)
{
//form not active
//do something
}
else
{
// form active
// do something
}
Related Topics
How to Log a User Out When They Close Their Browser or Tab in ASP.NET MVC
Launching Process in C# Without Distracting Console Window
Wpf Combobox: Different Template in Textbox and Drop-Downlist
Reasons for Why a Winforms Label Does Not Want to Be Transparent
Show Yes/No Instead True/False in Datagridview
Using Appdomain in C# to Dynamically Load and Unload Dll
How to Generically Format a Boolean to a Yes/No String
Is CSV with Multi Tabs/Sheet Possible
How to Programmatically Convert Vb6 Formatting Strings to .Net Formatting Strings
Return Only Digits 0-9 from a String
The Connection Was Not Closed the Connection's Current State Is Open
Htmlagilitypack - Remove Script and Style
Ssis Task for Inconsistent Column Count Import
C# Code to Linkify Urls in a String