在c#中切换应用程序,如任务管理器

Myt*_*ush 6 c# winforms

我想编写c#应用程序,它将在一些正在运行的应用程序之间切换.它应该像Windows中的Alt + Tab一样执行确切的功能.我使用SetForegroundWindow()Windows API中的函数,但如果在Windows任务栏上最小化应用程序,则它无法正常工作.所以我添加了ShowWindow()功能,但有一个问题是我无法以用户设置的原始大小显示窗口.

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

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

示例:我最大化窗口,然后将其最小化到任务栏中.我打电话的时候:

ShowWindow(processWindowHandle, ShowWindowCmd.SW_NORMAL);
WindowsApi.SetForegroundWindow(processWindowHandle);
Run Code Online (Sandbox Code Playgroud)

窗口未最大化.我尝试使用ShowWindowCmd.SW_NORMAL参数,但结果相同.

JMK*_*JMK 3

我之前已经这样做过,您想要获取所有打开的所有内容的列表,最小化所有内容,然后再次迭代,将每个程序与您想要恢复的程序进行比较,然后恢复该程序。你需要一种方法来识别你想要恢复的一个窗口,我曾经使用MainWindowTitle,因为我可以控制环境,因此可以保证每个MainWindowTitle都是唯一的,你可能没有那么奢侈。

我过去使用的代码如下,效果很好:

[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);
        }
}
Run Code Online (Sandbox Code Playgroud)