Sign in to follow this  
Subconscious

[.net] Switching foreground application?

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) ?
SW_SHOWMAXIMIZED : SW_SHOWNORMAL;
ShowWindow(hwndInstance, showCmd);
}
else
{
// if it's not minimized, then we just call SetForegroundWindow to
// bring it to the front.
SetForegroundWindow(hwndInstance);
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this