tags:

views:

231

answers:

2

I have the following problem: I want to be able to tell if my application window is the foreground window in Windows. I am using C#, .Net Framework 3.5 on Windows XP.

I actually can think of two ways to do what I am after

  1. Use pinvoke, GetForeGroundWindow and compare the returned hWnd to the hWnd of my form
  2. Check if Form.ActiveForm is null or an object reference

Method 1 seems OK, but I would rather not use pinvoke unless I have to. I am not entirely sure about method 2 although it seems to work OK.

Which method should I use, is there any other way?

A: 
Form.TopMost

from msdn:

Gets or sets a value indicating whether the form should be displayed as a topmost form.

amartin
I think this is not what Peter meant. He just wants to know wheter a form is on the foreground, not ensure it is always on the foreground.
Ikke
This is indeed not what I mean.
Peter van der Heijden
+1  A: 

It appear ActiveForm is application specific.

If you want to know if/when your form is the active form for the entire OS, you are stuck with API and a hWnd compare.

[DllImport( "user32.dll" )]    
public static extern IntPtr GetForegroundWindow();
JDMX
Yes - `ActiveForm` works within the bounds of you "application"
Paul Kohler
It did not occur to me that ActiveForm was application specific and GetForeGroundWindow OS wide. I think I ended up using ActiveForm.
Peter van der Heijden