Cameron
Cameron

Reputation: 98746

Determine if current application is activated (has focus)

Note: There's a very similar question, but it's WPF-specific; this one is not.

How can I determine if the current application is activated (i.e. has focus)?

Upvotes: 52

Views: 58349

Answers (7)

binki
binki

Reputation: 8308

The solution I found which requires neither native calls nor requires handling events is to check Form.ActiveForm. In my tests, that was null when no window in the application was focused and otherwise non-null.

var windowInApplicationIsFocused = Form.ActiveForm != null;

Ah, this is specific to winforms. But that applies to my situation ;-).

Upvotes: 13

Shalako Lee
Shalako Lee

Reputation: 138

In WPF the easiest way to check if a window is active is:

if(this.IsActive)
{
 //the window is active
}

Upvotes: 1

Proteux
Proteux

Reputation: 213

since it's likely that some element in your UI has contain focus for the form to be active try:

this.ContainsFocus

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110).aspx

Upvotes: 11

Cameron
Cameron

Reputation: 98746

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 :-)

Upvotes: 87

Cilvic
Cilvic

Reputation: 3447

First get the handle either using:

IntPtr myWindowHandle;

myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;

or

HwndSource source = (HwndSource)HwndSource.FromVisual(this);
myWindowHandle = source.Handle;

Then compare whethers it is the ForeGroundWindow:

if (myWindowHandle == GetForegroundWindow()) 
{
  // Do stuff!

}

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

Upvotes: 2

Paul Sasik
Paul Sasik

Reputation: 81459

Handle the Activated event of your main application Form.

Upvotes: 1

genesis
genesis

Reputation: 50976

You can subscribe to Main Window's Activated event

Upvotes: 5

Related Questions