views:

51

answers:

1

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.

+2  A: 

Use the GetConsoleWindow function.

Ben Voigt
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
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
Actually `GetConsoleWindow` does work. However `SetFocus` returns NULL and `GetLastError` gives ERROR_ACCESS_DENIED. Any ideas why?
Steven
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
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