Get last active window: Get Previously active window

前端 未结 2 977
我在风中等你
我在风中等你 2021-02-06 09:26

I am working on an application which needs to get the last active window handle. Suppose my application is running then I want to get last active window handle that was just pre

2条回答
  •  情书的邮戳
    2021-02-06 10:14

    I needed the same thing of the last handle from the previous window I had open. The answer from Jamie Altizer was close, but I modified it to keep from overwriting the previous window when my application gets focus again. Here is the full class I made with the timer and everything.

    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;
    }
    

提交回复
热议问题