Hi, I am trying to ensure a single instance of my ...
# multiplatform
a
Hi, I am trying to ensure a single instance of my Desktop JVM app, when running on Windows. I have created this simple code using Java JNA to set focus to existing window on startup if trying to start another instance:
Copy code
fun checkForSingleInstance(onExit: () -> Unit) {
    when (hostOs) {
        OS.Windows -> {
            val handle = User32.INSTANCE.FindWindow(null, windowTitle.uppercase())

            if (handle != null) {
                User32.INSTANCE.ShowWindow(handle, User32.SW_SHOWNORMAL)
                onExit()
            }
        }
        else -> {
            // do nothing
        }
    }
}
My issue is if the app is minimized to Tray using visible property on Window, then the window is shown correct when starting another instance, but I can not interact with anything other that the Toolbar Min/Max/Close buttons until I use a Tray action to reset the visible property (resizing the window also just add white space like the Compose engine is not running). What am I missing?
m
I had this issue on one of my personal projects. Solved it with a simple
.lock
file and
deleteOnExit
which would be checked for at startup. UI was very simple "app is already open. If this is incorrect, delete file xyz/.lock"
a
yes, but I also want to focus existing window and restore it to last shown position - which works fine on Windows except when minimized to tray - also the .lock solution has issues on hard crash of app (where the file is not guaranteed to be deleted)
👀 1
a
a
seems like this could be a solution or at least giving me idea to solve by communicating to existing app to untray the application
m
That utilizes a
.lock
file as well, lol.
a
yeah, I am not going to use it, but it internally send messages to existing application over socket - I can use that principle for a workaround to my issue
to set the visible param
m
Actually, if you're using Java 16+ you can replace the
.lock
file concept with Unix Domain Sockets which will resolve that hard crash problem (drops it to the FS to clean up when the process owner exits)