0

This is for a C# xUnit test project that spawns processes such as notepad.exe, winword.exe and winver.exe. I need to switch between these applications for the test (make them the foreground window).

So far, I have tried SetForegroundWindow, SwitchToThisWindow, SetActive, SetFocus etc from user32.dll, which doesn't work. I've tried using the AttachThreadInput trick, but it doesn't seem to work (maybe im doing it wrong? im using it from a console application after all). I've also tried the press alt then switch method, but I do not want to do it this way (notepad eats the alt).

  • STRONG SUGGESTION (*ESPECIALLY* since you're doing "testing"): look into Selenium. For example: https://www.automatetheplanet.com/automate-windows-desktop-apps-winappdriver/ – FoggyDay May 01 '20 at 05:49
  • Claiming that function does not work when it work exactly as described in the documentation is somewhat confusing. I strongly suggest to re-read https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow and adjust your expectations accordingly. – Alexei Levenkov May 01 '20 at 05:53
  • *"I need to switch between these applications for the test"* - You have misdiagnosed your requirements. What you really need is to automate a set of applications. If done right, none of those applications need to be eligible for user input. After all, this is an automated test that runs without user interaction. Doing it right involves [UI Automation](https://learn.microsoft.com/en-us/dotnet/framework/ui-automation/ui-automation-overview). All of the applications listed implement the interfaces required for UI Automation. – IInspectable May 01 '20 at 08:58
  • It depends on your OS you forgot to mention. Have looked at the examples @ [pinvoke.net?](https://pinvoke.net/default.aspx/user32.SetForegroundWindow) – Enriko Riba May 01 '20 at 07:08
  • hi, has your question been solved? – Strive Sun May 07 '20 at 09:49

1 Answers1

0

I haven't solved the issue, but I've just ended up using my own apps to test that don't eat the alt key. Here is the window switching code, for reference (it's in F# using the Vanara library but you can change some things to make it usable for C#).

let hwnd = mainWindowHWND
let keyState = Array.create 256 0uy

if User32.GetKeyboardState(keyState) && ((keyState.[VK_MENU |> int] &&& state) = 0uy) then
    User32.keybd_event(VK_MENU, 0uy, User32.KEYEVENTF.KEYEVENTF_EXTENDEDKEY, unativeint 0)

User32.SetForegroundWindow(hwnd()) |> ignore

if User32.GetKeyboardState(keyState) && ((keyState.[VK_MENU |> int] &&& state) = 0uy) then
    User32.keybd_event(VK_MENU, 0uy, User32.KEYEVENTF.KEYEVENTF_EXTENDEDKEY ||| User32.KEYEVENTF.KEYEVENTF_KEYUP, unativeint 0)