views:

250

answers:

3

I have a .NET application running on a Smartphone. I want a way for the application to close when it is pushed into the background.

I.e. if a user presses the off button once itll take them to the desktop. The application is still running in the background though.

I want a way to detect that the application is no longer in the foreground and exit it.

I attempted doing this via the LostFocus event but it becomes complicated when option forms are loaded and isn't always reliable.

Can anyone offer suggestions? Thanks

A: 

I think the LostFocus event is probably the most reliable solution available.

If it were me, I would use Reflection to check to see if the sender of the LostFocus event were any of the Forms in my assembly. If not, exit.

JoshJordan
+1  A: 

I would listen to the Form.Deactivate event (or override the Form.OnDeactivate Method if you own the class) and check the GetForegroundWindow function to determine if your form is in the background. If it isn't, then you know your form was sent to the background.

e.x.:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class Form1 : Form
{
[DllImport("coredll")]
static extern IntPtr GetForegroundWindow();

[DllImport("coredll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

protected override void OnDeactivate(EventArgs e)
{
    base.OnDeactivate(e);

    //if the foreground window was not created by this application, exit this application
    IntPtr foregroundWindow = GetForegroundWindow();
    int foregroundProcId;
    GetWindowThreadProcessId(foregroundWindow, out foregroundProcId);
    using (Process currentProc = Process.GetCurrentProcess())
    {
        if (foregroundProcId != currentProc.Id)
        {
            Debug.WriteLine("Exiting application.");
            Application.Exit();
        }
    }
}

}

hjb417
+1  A: 

You might look at this article on Detecting Form and Process Changes in CE.

ctacke