tags:

views:

39

answers:

2

I want to talk to the application that was used just before my application, how can I find out which application had focus last?

A: 

Before creating your own application window, call GetForegroundWindow. Otherwise call GetWindow(your_hwnd,GW_HWNDNEXT) to find the next window, below the specified.

Chris Becke
Be aware that there are some situations where this won't work, for example if the previous window was closed.
JBRWilkinson
+1  A: 

Hi There

I am looking for the same - I have an application that stays open on the screen and the user can invoke a button on my app once they have made an entry into one of three 3rd party applications.

When they click the button on my app, I need to determine which of the three applications they last used in order to know which database to talk to. I have gone down the route of looking at GetForeGroundWindow and GetWindow however the Window handle I get from GetWindow always refers to a window with title M. I have used the Winternal Explorer tool from the Managed Windows API tools and I can locate the M handle being returned and it is a 'child' of the process that I am after - but from this handle I cant get the process name.

I have done up a small example app using simple windows forms - and I lauch it and then make Notepad the focus and then click on my button and I get the handle - but when looking at the MainWindowHandle of all the processes, it is not listed, but using Winternal Explorer I can see that is a sub process of the notepad process.

Any suggestions on why I am only getting this subprocess handle returned instead of the actual process handle??

Sample code is below - being run on a Windows XP sp 3 machine

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TestWindowsAPI
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr thisWindow = GetForegroundWindow();
            IntPtr lastWindow = GetWindow(thisWindow, 2);

            tbThisWindow.Text = thisWindow.ToString();
            tbLastWindow.Text = lastWindow.ToString();
        }
    }
}
Paul T
If you used a WIN32 Windows Hook, you could have your code automatically invoked when they do an operation inside the 3rd party application. See this article for more: http://support.microsoft.com/kb/318804
JBRWilkinson