Jump to content
  • Advertisement
Sign in to follow this  

[.net] Switching foreground application?

This topic is 4610 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there any way to change the foreground application in a C# program? For example make it so when I hit a button, it switches the foreground application to the last window that was in foreground. I had some success with importing SetForegroundWindow from user32.dll, it makes the window I specify go to the front of the screen, but it still isn't activated and doesn't have input focus. I've tryed importing other functions like SetFocus and SetActive window with no luck. Anyone have any ideas?

Share this post

Link to post
Share on other sites
Here's some code I used in a similar project:

// External Win32 APIs that we're calling directly.
[DllImport("USER32.DLL", SetLastError=true)]
private static extern uint ShowWindow (uint hwnd, int showCommand);

[DllImport("USER32.DLL", SetLastError=true)]
private static extern uint SetForegroundWindow (uint hwnd);

[DllImport("USER32.DLL", SetLastError=true)]
private static extern uint GetWindowPlacement (uint hwnd,
[In, Out]ManagedWindowPlacement lpwndpl);

[DllImport("USER32.DLL", SetLastError=true)]
private static extern uint FindWindow (string lpClassName, string lpWindowName);

[DllImportAttribute ("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int
wParam, int lParam);

// Windows defined constants.
private const int WM_ACTIVATE = 0x0006;
private const int WA_CLICKACTIVE = 2;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int WPF_RESTORETOMAXIMIZED = 2;
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MAXIMIZE = 0xF030;

public static void ActivateWindow(uint hwndInstance)
// Then, get the WindowPlacement, so we can decide the best way to
// activate the window correctly.
ManagedWindowPlacement placement = new ManagedWindowPlacement();
GetWindowPlacement(hwndInstance, placement);

if (placement.showCmd == SW_SHOWMINIMIZED)
// if the window is minimized, then we need to restore it to its
// previous size. we also take into account whether it was
// previously maximized.
int showCmd = (placement.flags == WPF_RESTORETOMAXIMIZED) ?
ShowWindow(hwndInstance, showCmd);
// if it's not minimized, then we just call SetForegroundWindow to
// bring it to the front.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!