4

Is it possible to set focus on a console app in Windows? SetFocus looks promising, but it needs an HWND and I don't know if console apps even have one.

Steven
  • 2,538
  • 3
  • 31
  • 40
  • Are you looking for a way to do this from inside the console application itself, or from another application? – Paul-Jan Jul 11 '10 at 17:05

1 Answers1

4

Use the GetConsoleWindow function.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • That returns NULL for me. I'm guessing it works if I actually create a console for a Windows app with AllocConsole or something. – Steven Jul 11 '10 at 16:22
  • If it's running in a windowed console session, you ought to get a valid HWND. If it's in a service login session then there wouldn't be any window associated. And Windows automatically calls `AllocConsole` or `AttachConsole` whenever it starts a process linked with the `/SUBSYSTEM:CONSOLE` option (stored as a flag in the PE header). – Ben Voigt Jul 11 '10 at 16:42
  • 1
    Actually `GetConsoleWindow` does work. However `SetFocus` returns NULL and `GetLastError` gives ERROR_ACCESS_DENIED. Any ideas why? – Steven Jul 11 '10 at 17:09
  • Yes, you can't steal focus from other applications because it's so doggone annoying, Microsoft finally listened to their users and blocked it. `SetFocus` is usable for changing focus within a single application, or giving away focus if you have it, but not for taking it. Consider using `FlashWindowEx` instead http://msdn.microsoft.com/en-us/library/ms679347.aspx – Ben Voigt Jul 11 '10 at 17:17
  • 1
    More information: http://stackoverflow.com/questions/688337/how-do-i-force-my-app-to-come-to-the-front-and-take-focus http://blogs.msdn.com/b/oldnewthing/archive/2009/02/20/9435239.aspx – Ben Voigt Jul 11 '10 at 17:19