c# - How can I determine when my application's console window gets or loses focus? -


is there simple way this? or @ least check if console in focus?

imagine game (thats not case here analogy holds) - useful if pause automatically. need similar.

if window interested in not console window, have been simple tapping appropriate focus event. console windows don't have focus events, easy way out not available here.

what can set event handler receive winevents generated ui automation services. event generated whenever window focus changes; can hwnd of newly focused window , compare of console window. if match, got focus; if don't, don't have focus (either lost or never had begin with).

the convenient way tap ui automation through system.windows.automation namespace. can set event handler addautomationfocuschangedeventhandler, give instance of automationfocuschangedeventargs can determine window has received focus.

here's sample code:

automationfocuschangedeventhandler focushandler = onfocuschange; automation.addautomationfocuschangedeventhandler(focushandler); messagebox.show("listening focus changes"); automation.removeautomationfocuschangedeventhandler(focushandler); 

where onfocuschange is:

void onfocuschange(object source, automationfocuschangedeventargs e) {     var focusedhandle = new intptr(automationelement.focusedelement.current.nativewindowhandle);     var myconsolehandle = process.getcurrentprocess().mainwindowhandle;      if (focusedhandle == myconsolehandle)     {         // ...     } } 

note assuming console process's main window simplicity; if that's not case, need hwnd console window other way.

also note in order receive automation events, process must running message loop (in case known "dispatcher loop"), in turn requires thread being dedicated running it. in example above happens automatically when messagebox.show called, in general case have take proper care of it.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -