如何将 Kotlin Multiplatform(桌面版)变成“单实例应用程序”?

问题描述 投票:0回答:1

是否有方法或任何文档描述如何将适用于 Windows 桌面的 Kotlin 多平台应用程序转变为“单实例应用程序”?

我的意图是,如果用户在应用程序已经运行时再次单击应用程序的启动器/可执行文件,它只会将现有的正在运行的实例拉到用户的视图中,而不是启动应用程序的新实例。但我还没有找到任何 Java 或 Gradle 或多平台等功能标志或代码来弄清楚如何做到这一点。

更新/部分答案:

到目前为止,我实现了以下内容,或多或少可以处理它。理想情况下,我想通过 Gradle 制作启动器,但这至少提供了上述功能。

  1. 在应用程序启动时添加了以下检查,以防止用户启动应用程序两次。摘自https://stackoverflow.com/a/52950331/13225055
fun lockInstance(): Boolean {
   return try {
      val file = File("/path/to/my/lockfile.lock")
      val randomAccessFile = RandomAccessFile(file, "rw")
      val fileLock = randomAccessFile.channel.tryLock()
      if (fileLock != null && fileLock.isValid && !fileLock.isShared) {
         Runtime.getRuntime().addShutdownHook(Thread {
            try {
               fileLock.release()
               randomAccessFile.close()
               file.delete()
            } catch (e: Exception) {
               false // log error
            }
         })
         true
      }
   } catch (e: Exception) {
      false // and log whatever
   }
}
  1. 使用 Powershell 脚本并将其转换为
    .exe
    文件,我将其复制到应用程序的
    appResourcesRootDir
    目录中,以便在安装时可以将其从应用程序目录中复制出来。主要取自https://stackoverflow.com/a/42567337/13225055
$programName = "MyApp"

if (Get-Process -Name $programName -ErrorAction SilentlyContinue) {
   $programProcesses = Get-Process -Name $programName | Sort-Object -Property WorkingSet -Descending

   Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WinAp {
   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   public static extern bool SetForegroundWindow(IntPtr hWnd);

   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
"@

   $hWnd = $programProcesses[0].MainWindowHandle
   [void] [WinAp]::SetForegroundWindow($hWnd);
   [void] [WinAp]::ShowWindow($hWnd, 3);
} else {
   # If I ran Start-Process it wouldn't show the app's splash screen
   Set-Location "c:\Program Files\MyApp"
   .\MyApp.exe
}
kotlin-multiplatform single-instance
1个回答
0
投票

我也遇到这个问题,我也在寻找一个 powershell 脚本来在安装程序运行时自动运行。我对jvm还是个新手。哈哈

© www.soinside.com 2019 - 2024. All rights reserved.