切换到同一应用程序的其他实例

SMU*_*hah 1 c# winforms

如果发生某个事件,我希望我的c#winform应用程序切换到另一个正在运行的实例.

例如,如果我的应用程序只有一个按钮,那么目前正在运行三个实例.现在,如果我

  1. 在第一个实例中按下按钮,焦点到第二个实例
  2. 在第二个实例中按下按钮,焦点到第三个实例
  3. 在第三个实例中按下按钮,焦点到第一个实例

我怎么做?

Dav*_*ras 7

如果你知道其他实例的句柄,你应该只调用Windows API:SetForegroundWindow:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
Run Code Online (Sandbox Code Playgroud)

您可以使用FindWindow API调用来获取其他实例的句柄,例如:

 public static int FindWindow(string windowName)
    {
        int hWnd = FindWindow(null, windowName);

        return hWnd;
    }
Run Code Online (Sandbox Code Playgroud)

您可以在SO中搜索这些api调用以获取更多示例,例如找到这个:

如何聚焦外窗?