Code updated for 5.20+
This code will prevent a second application instance from running, and will re-activate the running instance to the foreground even if it is hidden or minimized. It also passes the new command line parameters/arguments to the running instance, to be processed as required. To test it, you'll have to compile it, and launch a second instance with parameters from the command prompt:
Code: Select all
;==========================================
;
; Passing command line parameters to a
; running instance of an application
;
; by TI-994A - 5th April, 2012
;
;==========================================
EnableExplicit
Enumeration
#MainWindow
#TextBox1
EndEnumeration
Define.i appInstance, hWndRunningInstance, paraLoop, wFlags
Define.s mutexName, cmdLineParameters, cmdLineDATA.COPYDATASTRUCT
mutexName = "myUniqueAppFlag"
appInstance = CreateMutex_(0, 1, @mutexName)
If appInstance <> 0 And GetLastError_() = #ERROR_ALREADY_EXISTS
hWndRunningInstance = FindWindow_(0, "Command Line Arguments")
For paraLoop = 1 To CountProgramParameters()
cmdLineParameters = cmdLineParameters + "," + ProgramParameter()
Next paraLoop
cmdLineDATA\cbData = Len(cmdLineParameters)
cmdLineDATA\lpData = @cmdLineParameters
SendMessage_(hWndRunningInstance, #WM_COPYDATA, 0, @cmdLineDATA)
CloseHandle_(appInstance)
End
EndIf
Procedure WndProc(hWnd, uMsg, wParam, lParam)
Define.i result = #PB_ProcessPureBasicEvents
Define cmdLineARGs.s, *cmdLineDATA.COPYDATASTRUCT
Select uMsg
Case #WM_COPYDATA
If Not IsWindowVisible_(WindowID(#MainWindow))
HideWindow(#MainWindow, 0)
EndIf
If GetWindowState(#MainWindow) = #PB_Window_Minimize
SetWindowState(#MainWindow, #PB_Window_Normal)
EndIf
SetForegroundWindow_(WindowID(#MainWindow))
*cmdLineDATA = lParam
cmdLineARGs = PeekS(*cmdLineDATA\lpData, *cmdLineDATA\cbData)
If Trim(cmdLineARGs) = ""
cmdLineARGs = "none received."
EndIf
SetGadgetText(#TextBox1, "New Parameters: " + cmdLineARGs)
EndSelect
ProcedureReturn result
EndProcedure
wFlags = #PB_Window_ScreenCentered | #PB_Window_MaximizeGadget | #PB_Window_MinimizeGadget
OpenWindow(#MainWindow, #PB_Any, #PB_Any, 500, 100, "Command Line Arguments", wFlags)
TextGadget(#TextBox1, 50, 30, 400, 30, "")
SetWindowCallback(@WndProc())
While WaitWindowEvent() ! #PB_Event_CloseWindow : Wend
Hope this is helpful for you.
EDIT: code updated to comply with PureBasic's new label/colon syntax.