Reputation: 6476
I'm using the Shell command in vba to launch an app. I then hook the app using the WIN32 API so that I can control it.
This is all working fine but for one small detail: I'd like to return focus to the excel dashboard, where I have the buttons to control the app, after the app launches, As it is, I need to click on the spreadsheet before I can click any buttons.
I've tried using AppActivate Application.ActiveWindow.Caption
and SetForegroundWindow
, SetFocus
and WM_IME_SETCONTEXT
with WM_IME_NOTIFY
via SendMessage
but nothing seems to work. I also tried the worksheet Activate
method as well as the Range Activate
method but, I still have to click on the worksheet before I can click a button.
I would have thought this was possible because I'm sending the message from the excel process, how can I activate the spreadsheet?
Upvotes: 0
Views: 243
Reputation: 6476
The rules governing which objects can set the foreground window were not being met and this is why I couldn't get it to work.
The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:
The process is the foreground process.
The process was started by the foreground process.
- The process received the last input event.
- There is no foreground process.
- The process is being debugged.
- The foreground process is not a Modern Application or the Start Screen.
- The foreground is not locked (see LockSetForegroundWindow).
- The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
- No menus are active.
An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.
In my case I was trying to get excel to activate one of its own windows but, the spawned app had already taken over foreground focus, so excel was powerless to influence foreground focus. The solution was to send a custom message to the app from VBA, with the excel hWnd as an argument, requesting foreground focus. The app can then call SetForegroundWindow
and because it satisfies the first condition above, excel is indeed given foreground focus.
Upvotes: 1