Get last active window: get previously active window

I am working on an application that should receive the last active window handle. Suppose my application is running, then I want to get the last active window handle that was just opened before my application.

@ EDIT1: This is not a duplicate question. I need to get the handle to the last active window, not the current window.

+5
source share
2 answers

This is similar to an alternative SO question , I would suggest that you simply track the active window and after the change you will find out the previously active

, , , , , , , , lastHandle , lastHandle. , :

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

static IntPtr lastHandle = IntPtr.Zero;

//This will be called by your logic on when to check, I'm assuming you are using a Timer or similar technique.
IntPtr GetLastActive()
{
  IntPtr curHandle = GetForeGroundWindow();
  IntPtr retHandle = IntPtr.Zero;

  if(curHandle != lastHandle)
  {
    //Keep previous for our check
    retHandle = lastHandle;

    //Always set last 
    lastHandle = curHandle;

    if(retHandle != IntPtr.Zero)
      return retHandle;
  }
}
+3

, . Jamie Altizer , , , . , .

static class ProcessWatcher
{
    public static void StartWatch()
    {
        _timer = new Timer(100);
        _timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        _timer.Start();
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        setLastActive();
    }

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

    public static IntPtr LastHandle
    {
        get
        {
            return _previousToLastHandle;
        }
    }

    private static void setLastActive()
    {
        IntPtr currentHandle = GetForegroundWindow();
        if (currentHandle != _previousHandle)
        {
            _previousToLastHandle = _previousHandle;
            _previousHandle = currentHandle;
        }
    }

    private static Timer _timer;
    private static IntPtr _previousHandle = IntPtr.Zero;
    private static IntPtr _previousToLastHandle = IntPtr.Zero;
}
+1

All Articles