Take the 2-minute tour ×

I'm making a C# WPF application, and every time the users clicks somewhere outside of my application, I want to display an alert with the TITLE of the window clicked. To detect clicks outside my application, I'm using LowLevelMouseProc. But how would I get the window that has focus in C#?

Thanks in advance!

EDIT: I know this is not related to my original question, but how would I get the control focused, as well?

share|improve this question
to the second question: you probably need a function GetFocus() - read Remarks on that MSDN page –  kirmir May 29 '11 at 23:06
Are you sure you only want to detect when the user clicks outside your app? Users can use the keyboard to switch windows too. You might try looking into the WM_ACTIVATE message: stackoverflow.com/questions/813356/… (Winforms, but the same basic idea works for WPF as well when you get the HWNDs from WPF windows) –  Zach Johnson May 29 '11 at 23:27

2 Answers 2

up vote 3 down vote accepted

Regarding your follow-up question on how to get the control with focus, you can get the HWND of the focused control using GetGUIThreadInfo. Note that you pass this the thread that owns the foreign window, not the foreign window itself (the function docs tell you how to to get the thread ID from the foreign window handle). The focused HWND is returned through the GUITHREADINFO.hwndFocus member.

Note that in general, you can't do better than a HWND, because the foreground window is not necessarily a .NET application. For example, if the foreign window is a WPF window, this will not tell you which WPF control within that window has focus, because WPF controls don't have HWNDs.

share|improve this answer

GetForegroundWindow should do it.

share|improve this answer
Thank you, that works! I know this is not related to my original question, but how would I get the control focused, as well? –  mattsven May 29 '11 at 21:55

Your Answer


