David
David

Reputation: 830

How to control windows application focus in .NET

I'm using pinvoke "user32.dll" to send my application to back (behind all other apps) so it sits on desktop and vice versa. At the moment it just toggles - back/front. Is there a way to detect if my app is at the back and bring it to front or if it's on front and send it to back? THanks.

Upvotes: 0

Views: 1798

Answers (1)

Nanook
Nanook

Reputation: 3322

You can detect if your window is the active window by calling

[DllImport("user32.dll")] static
static extern IntPtr GetForegroundWindow();

You used to be able to call

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

to set your window to the foreground, but Microsoft changed it's functionality in Windows ME/2000 onwards (May have been XP?).

There are various work arounds attempts for this issue, you may need to test a few to see which works for you.

http://www.tek-tips.com/faqs.cfm?fid=4262

http://markribau.org/blog/?p=7

I remember reading about a registry entry that can be set to allow SetForegroundWindow to work as desired, but it's a system wide setting.

http://www.delphipages.com/forum/showthread.php?t=198261

You can use SetWindowPos to place you window behind other windows or permanently on top if that helps

http://www.pinvoke.net/default.aspx/user32.SetWindowPos

http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx

Upvotes: 2

Related Questions