https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

Anders Carlsen

03/12/2024, 3:23 PM
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

Matt Nelson

03/12/2024, 3:32 PM
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

Anders Carlsen

03/12/2024, 3:35 PM
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

Alexander Zhirkevich

03/12/2024, 3:48 PM
a

Anders Carlsen

03/12/2024, 3:54 PM
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

Matt Nelson

03/12/2024, 3:54 PM
That utilizes a
.lock
file as well, lol.
a

Anders Carlsen

03/12/2024, 3:55 PM
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

Matt Nelson

03/12/2024, 3:56 PM
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)
2 Views