2009-07-14 75 views
0

我有一個智能手機上運行的.NET應用程序。 我想讓應用程序在推入後臺時關閉。停止在後臺運行應用程序

I.e.如果用戶一旦按下關閉按鈕,就會將它們帶到桌面。應用程序仍然在後臺運行。

我想要一種方法來檢測應用程序不再處於前臺並退出它。

我試圖通過LostFocus事件做這件事,但是當選項窗體加載並且不總是可靠時,它變得複雜。

任何人都可以提供建議嗎? 謝謝

+0

看看這個問題http://stackoverflow.com/questions/433135/how-to-tell-if-any-form-from-my-app-is-in-foreground/433243 – 2009-07-14 16:02:59

回答

0

我認爲LostFocus事件可能是最可靠的解決方案。

如果是我,我會使用Reflection來檢查LostFocus事件的發件人是否是我的程序集中的任何窗體。如果沒有,退出。

1

我會聆聽Form.Deactivate event(或者如果您擁有該課程,請覆蓋Form.OnDeactivate Method)並檢查GetForegroundWindow函數以確定您的表單是否位於後臺。如果不是,那麼你知道你的表單被髮送到了後臺。

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

}