c# - 只运行一个应用程序实例,(退出新实例并显示旧实例或给予焦点)

标签 c# winforms

我的应用程序有一个默认设置,当您启动计算机时,它会在图标托盘上运行。 如果您单击图标托盘中的图标,则该应用程序将显示在桌面窗口中。 此外,如果用户在旧应用程序运行时尝试启动我的应用程序的新实例,我只会显示一条消息,说明另一个实例正在运行,然后退出新实例。

现在我不仅要让新实例退出,还要使旧实例处于事件状态/显示在桌面上。 这是我现在的代码

if (System.Diagnostics.Process.GetProcessesByName(
           System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
{
    MessageBox.Show(kingCobra.Properties.Resources.Msg_Multiple_Starts, 
                    kingCobra.Properties.Resources.Multiple_Starts,
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
    System.Diagnostics.Process.GetCurrentProcess().Kill();
    return;
}

最佳答案

你需要做的是将它添加到你的主类中:

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

然后您需要获取对已经运行的进程的引用,然后像这样调用 SetForegroundWindow 方法:

  SetForegroundWindow(SameProcess.MainWindowHandle);

你不需要像你现在做的那样杀死当前进程,如上所示聚焦其他进程的主窗口后返回即可

这是一个完整的工作示例:

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


/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
    var currentProcess = Process.GetCurrentProcess();

    foreach (Process p in Process.GetProcessesByName(currentProcess.ProcessName))
    {
        if (p.Id != currentProcess.Id)
        {
            MessageBox.Show("Already running");
            SetForegroundWindow(p.MainWindowHandle);
            return;
        }
    }

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

关于c# - 只运行一个应用程序实例,(退出新实例并显示旧实例或给予焦点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510082/

相关文章:

winforms - 如何创建水印文本框

c# - 从身份验证中排除文件类型的中间件

c# - Azure CosmosDB (Gremlin API),如何使用 Gremlin.Net 进行连接

c# - javascript :void(0) called 时 WebBrowser 控件未完成加载

c# - 使用 C# WebBrowser 时是否可以检测到调用的任何 javascript 函数

c# - 使用 C# 从 SharePoint (CSOM) 下载特定文件

c# - SQL 和 LINQ 的 ExecutionEngineException

c# - 如何检测用户何时单击 WebView 控件中的超链接?

c# - Linq to Entities 中的规范函数不起作用

c# - WinForms/C# 中的动画效果