How do I know if my form is currently on top of others?

Basically, how do I know if my program overlays on top of all the others?

+4
source share
4 answers

A fairly simple way is to P / Invoke GetForegroundWindow () and compare the HWND returned in the application form. Property Handle.

using System; using System.Runtime.InteropServices; namespace MyNamespace { class GFW { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); public bool IsActive(IntPtr handle) { IntPtr activeHandle = GetForegroundWindow(); return (activeHandle == handle); } } } 

Then from your form:

 if (MyNamespace.GFW.IsActive(this.Handle)) { // Do whatever. } 
+10
source

You can use:

 if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle) { //do stuff } 

WINAPI import (at the class level):

 [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool GetForegroundWindow(); 

Assign a property to store the value and add validation to the GotFocus event form via the IDE or after InitializeComponent ();

eg:.

 //..... InitalizeComponent(); this.GotFocus += (myFocusCheck); //... private bool onTop = false; private void myFocusCheck(object s, EventArgs e) { if(GetFore......){ onTop = true; } } 
+1
source

If your window inherits a form, you can check the Form.Topmost property

0
source

A good solution is given by this answer to an identical question: fooobar.com/questions/159037 / ...

 /// <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); 

Currently, the decision made by Euric does not work if your program displays a dialog box or has removable windows (for example, if you use the window docking infrastructure).

0
source

All Articles