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

标签 c# winforms

我希望我的 c# winform 应用程序在发生特定事件时切换到另一个正在运行的实例。

例如,如果我有一个只有一个按钮的应用程序,并且此时正在运行三个实例。现在如果我

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

我该怎么做?

最佳答案

如果您知道其他实例的句柄,您应该只调用 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 调用以获取更多示例,例如找到这个:

How do I focus a foreign window?

关于c# - 切换到同一应用程序的其他实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7339920/

相关文章:

c# - LINQ 查询返回

c# - 在 Entity Framework 中将属性标记为 "Value generated on add or update"有什么意义?

c# - 使用 Invoke 方法从外部线程关闭窗体

c# - MemberwiseClone 与新对象

c# - 如何在 GridView 列中显示新行

c# - 启动与文件关联的外部进程并将此应用程序发送到后台

c# - 完成选择项目时的事件?

c# - 将 DateTimePicker 控件设置为格式 YYYYMMDD?

c# - 带有 Windows 窗体的 WPF - STAThread

c# - WPF在 View 模型中获取鼠标坐标