Description
This is a small sample on using DDE to check for a running previous instance (w/o using App.PrevInstance) and how to pass current command-line to this already running instance.
Usage
In an Std-EXE project's default Form1 form place a TextBox and a ListBox and set form's LinkMode property at design-time (cannot be set at run-time) to 1 - Source and then paste this code:
The code is based on Using DDE on Your VB Application article but is refactored into a pvNotifyPreviousInstance function which returns True if a previous instance is notified/running.
Download
The whole project zipped: DDETest2.zip
cheers,
</wqw>
This is a small sample on using DDE to check for a running previous instance (w/o using App.PrevInstance) and how to pass current command-line to this already running instance.
Usage
In an Std-EXE project's default Form1 form place a TextBox and a ListBox and set form's LinkMode property at design-time (cannot be set at run-time) to 1 - Source and then paste this code:
Code:
Option Explicit
Private Declare Function RtlGenRandom Lib "advapi32" Alias "SystemFunction036" (RandomBuffer As Any, ByVal RandomBufferLength As Long) As Long
Private Const STR_LINK_TOPIC As String = "DDELink"
Private Sub Form_Load()
Const MAX_CONCURRENCY As Long = 5
Dim lIdx As Long
On Error GoTo EH
LinkTopic = vbNullString
If pvNotifyPreviousInstance(STR_LINK_TOPIC, Command$) Then
Unload Me
Exit Sub
Else
LinkTopic = STR_LINK_TOPIC & (pvGetRandom Mod MAX_CONCURRENCY)
For lIdx = 0 To MAX_CONCURRENCY - 1
DoEvents
If pvNotifyPreviousInstance(STR_LINK_TOPIC & lIdx, vbNullString) Then
LinkTopic = vbNullString
Do
If pvNotifyPreviousInstance(STR_LINK_TOPIC, Command$) Then
Unload Me
Exit Sub
End If
Loop
End If
Next
End If
LinkTopic = STR_LINK_TOPIC
pvOpenDocument Command$
Exit Sub
EH:
MsgBox Err.Description, vbCritical, "Form_Load"
End Sub
Private Sub Form_LinkExecute(CmdStr As String, Cancel As Integer)
On Error GoTo EH
If LinkTopic = STR_LINK_TOPIC Then
If WindowState = vbMinimized Then
WindowState = vbNormal
End If
If Visible Then
SetFocus
End If
pvOpenDocument CmdStr
End If
Cancel = 0
Exit Sub
EH:
MsgBox Err.Description, vbCritical, "Form_LinkExecute"
End Sub
Private Sub pvOpenDocument(sFileName As String)
If LenB(sFileName) <> 0 Then
List1.AddItem Timer & vbTab & sFileName
End If
End Sub
Private Function pvNotifyPreviousInstance(sTopic As String, sMessage As String) As Boolean
On Error GoTo EH
txtHidden.LinkTopic = App.Title & "|" & sTopic
txtHidden.LinkMode = vbLinkManual
txtHidden.LinkExecute sMessage
txtHidden.LinkMode = vbLinkNone
'--- success
pvNotifyPreviousInstance = True
EH:
End Function
Private Function pvGetRandom() As Long
Call RtlGenRandom(pvGetRandom, 2)
End Function
Download
The whole project zipped: DDETest2.zip
cheers,
</wqw>