is there a similar function to the vb6 app.previnstance function in .net?
Printable View
is there a similar function to the vb6 app.previnstance function in .net?
There is an example at planet source code
In Visual Basic 6.0, the PrevInstance property of the App object was used to determine if a previous instance of an application was running. There is no equivalent for this property in Visual Basic .NET; however, the following code can be used to test for a previous instance:
' Visual Basic .NET
Function PrevInstance() As Boolean
If Ubound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
Return True
Else
Return False
End If
End Function
Note The behavior is slightly different than that of Visual Basic 6.0. In Visual Basic 6.0, PrevInstance returned true only if the full path and file name were exactly the same; in Visual Basic .NET, this function will return true for two instances started from different paths. In addition, PrevInstance would never return true for the first instance of an application; in Visual Basic .NET, once a second instance is loaded, the first instance will also return true.
VB Code:
System.Runtime.InteropServices.Marshal.GetHINSTANCE _(System.Reflection.Assembly.GetExecutingAssembly.GetModules() _(0)).ToInt32()
The planet source code link provided by Frans C lists the above procedure for getting the app's instance.
How do you implement this so that when the user tries to open a second instance of the program:
1) A second instance is not created and
2) The existing instance is maximised
Thanks for the link. That was really helpful.
VB Code:
Public Function IsDuplicateInstance() As Boolean Static gInst As Threading.Mutex gInst = New Threading.Mutex(True, Application.ProductName) If Not gInst.WaitOne(10, False) Then On Error Resume Next 'Only works if the title of the application is the same as the ProductName. AppActivate(Application.ProductName) Return True End If End Function
If I call this procedure in Sub Main and "End" if it returns True, it works fine except that the existing instance is not maximised. When you say that the title of the application must be the same as the product name, do you mean the AssemblyTitle and AssemblyProduct as they appear in the AssemblyInfo file?
Hmm I may be a bit rusty but I believe the Application.ProductName must be either the threadname or the title of the main application window. The threadname is generally the same as the exe.
I had to change that slightly as the code did not work on XP.
Code:Dim requestInitialOwnership As Boolean = True
Dim mutexWasCreated As Boolean
Dim m As New Threading.Mutex(requestInitialOwnership, "MyAppName", mutexWasCreated)
If Not (requestInitialOwnership And mutexWasCreated) Then
'Application is already running, close this one
Exit Sub
End If
I use XP, it worked fine here.