Ensuring only one instance of your application runs at once

by Andrew Jackson 18. November 2005 17:06

In your main form put the following piece of code, replacing the YOURMAINFORM with the name of the form.

Shared Sub Main() ' check for previous instance If PrevInstance() Then MsgBox("Application is already running!", MsgBoxStyle.OKOnly Or MsgBoxStyle.Critical) Else ' Runs the application. Application.Run(New YOURMAINFORM) End If End Sub Private Shared Function PrevInstance() As Boolean ' array of running processes with this assembly name Dim p() As Process = Nothing Try ' put the processes into an array p = Diagnostics.Process.GetProcessesByName(System.Reflection.Assembly.GetExecutingAssembly.GetName.Name()) ' if there's more than one process with this name If p.Length > 1 Then ' program is running...return True PrevInstance = True Else PrevInstance = False End If Catch ex As System.Exception ' set return to False PrevInstance = False Finally ' clean up p = Nothing End Try End Function

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Simple Logging to a file in VB.net

by Andrew Jackson 18. November 2005 17:05

To add simple logging to a log file you can intercept your trace messages and put these to a log file.

To do this add the following code;

Imports System.IO Dim LogStream As FileStream 'should be at a level with enough scope for your logging 'Start the logging to your file - probably to go in your frmMain.load LogStream = New FileStream(System.IO.Path.Combine(System.Environment.CurrentDirectory, "MYFILE.log"), FileMode.OpenOrCreate) Dim objTraceListener As TextWriterTraceListener = New TextWriterTraceListener(LogStream) Trace.Listeners.Add(objTraceListener) 'Whenever you want to log a message use the vb.net trace.writeline("message") 'and it will get written to the log file. 'Close the log file when your application ends If Not LogStream Is Nothing Then Trace.Flush() LogStream.Close() End If

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen