Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch application in c# like task manager

Tags:

c#

winforms

I would like to write c# application which will switch between some running applications. It should do the exact functionality like Alt+Tab in windows. I use SetForegroundWindow() function from Windows API, but it does not work well if the application is minimized on the windows task bar. So I added ShowWindow() function, but there is one problem that I am not possible to show the window in the original size which user set.

[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

Example: I maximize window, then I minimize it into the task bar. When I call:

ShowWindow(processWindowHandle, ShowWindowCmd.SW_NORMAL);
WindowsApi.SetForegroundWindow(processWindowHandle);

The window is not maximized. I tried to play with the ShowWindowCmd.SW_NORMAL parameter but with the same result.

like image 471
Myth Rush Avatar asked Mar 26 '13 13:03

Myth Rush


1 Answers

I have done this before, you want to get a list of everything open, minimize everything, and then iterate through that again comparing each program with the one you want restores, and then restore that one. You need a way to identify that one window you want restored, I used to use the MainWindowTitle as I had control over the environment, and could therefore guarantee that each MainWindowTitle would be unique, you may not have that luxury.

The code I used in the past for this is below, it worked well:

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

void SwitchDatabase(string mainWindowTitle)
{
        try
        {
            bool launched = false;

            Process[] processList = Process.GetProcesses();

            foreach (Process theProcess in processList)
            {
                ShowWindow(theProcess.MainWindowHandle, 2);
            }

            foreach (Process theProcess in processList)
            {
                if (theProcess.MainWindowTitle.ToUpper().Contains(mainWindowTitle.ToUpper()))
                {
                    ShowWindow(theProcess.MainWindowHandle, 9);
                    launched = true;
                }
            }
        }
        catch (Exception ex)
        {
            ThrowStandardException(ex);
        }
}
like image 91
JMK Avatar answered Oct 05 '22 11:10

JMK