[.net] Switching foreground application?

Started by
2 comments, last by DaWanderer 18 years, 6 months ago
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?
Advertisement
You might try the ShowWindow API function. I can't remember which parameter you pass, but I think this is how I solved the problem.
using ShowWindow with SW_SHOW got it to work sometimes, but not very consistently, still trying to figure out why
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);	}}

This topic is closed to new replies.

Advertisement