Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Getting the window with focus?

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?

like image 945
mattsven Avatar asked May 29 '11 21:05

mattsven


2 Answers

GetForegroundWindow should do it.

like image 172
Josh Avatar answered Sep 28 '22 00:09

Josh


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.

like image 31
itowlson Avatar answered Sep 28 '22 00:09

itowlson