35
A
回答
61
這工作:
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
它的是線程安全的,不需要的主要形式(或它的句柄)的優勢,而不是WPF或WinForms的具體。它將與子窗口(甚至獨立線程上創建的獨立子窗口)一起工作。此外,還需要零設置。
的缺點是,它使用一點點的P/Invoke,但我可以用:-)
3
1
處理你的主申請表的Activated event。
0
首先得到使用的句柄:
IntPtr myWindowHandle;
myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
或
HwndSource source = (HwndSource)HwndSource.FromVisual(this);
myWindowHandle = source.Handle;
然後比較whethers它是ForeGroundWindow:
if (myWindowHandle == GetForegroundWindow())
{
// Do stuff!
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
11
,因爲它很可能是在UI的一些元素具有包含焦點的形式是積極的嘗試:
this.ContainsFocus
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110).aspx
+1
這隻適用於如果你有一個表單(並沒有對話框等)。 – Cameron
0
在WPF中最簡單的方法來檢查,如果一個窗口是活動的是:
if(this.IsActive)
{
//the window is active
}
1
我找到的解決方案,它既不需要本地調用,也不需要處理事件是檢查Form.ActiveForm
。在我的測試中,當應用程序中沒有窗口爲焦點時爲null
,否則爲非空。
var windowInApplicationIsFocused = Form.ActiveForm != null;
啊,這是特定於winforms的。但這適用於我的情況;-)。
相關問題
- 1. 確定網頁是否具有前景窗口焦點/活動選項卡?
- 2. 如何確定進程是否爲當前活動/前臺應用程序
- 3. Angular + bootstrap-ui,檢查當前選項卡是否已經激活
- 4. Windows.Forms:激活已經在正確運行的應用程序FormWindowState
- 5. 當應用程序已經運行時激活GPS
- 6. 確定DataGrid是否具有基於ScrollViewer.ScrollChanged的焦點
- 7. 如何確定NSSearchField/NSTextField是否具有輸入焦點?
- 8. 沒有焦點/激活的表單
- 9. 激活Windows應用程序總是
- 10. qt應用程序激活
- 11. 應用程序激活
- 12. 是否可以通過bat腳本確定焦點窗口/應用程序?
- 13. 如何激活setInterval()使文本控件具有焦點
- 14. 如何檢查我的應用程序是否有焦點?
- 15. 焦點當前程序/文件名(Windows)
- 16. 確定哪些元素具有焦點
- 17. 確定哪個控件具有焦點
- 18. 確定是否有鍵按下當前
- 19. 刪除焦點從當前活動
- 20. 如何激活應用程序並將焦點集中在gtk/ubuntu上?
- 21. 如何確定應用程序是否是Web應用程序
- 22. 如果我的應用程序已具有焦點,如何檢測新的Intent?
- 23. 如何檢查哪個進程當前具有焦點
- 24. 如何確定當前的應用程序是否爲中信任
- 25. 確定我的應用程序是否在前臺
- 26. 如何以編程方式確定Android中當前活動的應用程序
- 27. VSTO:應用程序焦點
- 28. 如何找出哪個應用程序具有焦點
- 29. 當應用程序未運行時自動激活進程
- 30. 確定在點擊通知時是否顯示應用程序
你是說你的個人windowsform應用程序或任意? – Tigran
是這樣的? http://stackoverflow.com/questions/2183541/c-detecting-which-application-has-focus – 2011-08-23 14:43:45
個人 - 因此「當前的應用程序」;-) – Cameron