我希望我的 c# winform 应用程序在发生特定事件时切换到另一个正在运行的实例。
例如,如果我有一个只有一个按钮的应用程序,并且此时正在运行三个实例。现在如果我
- 第一次按下按钮,聚焦到第二次
- 在第二个实例中按下按钮,聚焦到第三个实例
- 在第三个实例中按下按钮,聚焦到第一个实例
我该怎么做?
最佳答案
如果您知道其他实例的句柄,您应该只调用 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);
您可以使用 FindWindow API 调用来获取其他实例的句柄,例如:
public static int FindWindow(string windowName)
{
int hWnd = FindWindow(null, windowName);
return hWnd;
}
您可以在 SO 中搜索这些 api 调用以获取更多示例,例如找到这个:
关于c# - 切换到同一应用程序的其他实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7339920/