.comment-link {margin-left:.6em;}

kHSw

Friday, December 17, 2004

How to check if you application is already running

In VB6 there was an easy way to check if your application was already running:
If App.PrevInstance Then ...
Looks like they've forgotten this handy feature in .NET.

Here's some C#-code to perform this check, if the application is found, it will bring the already running instance to the foreground using a Windows API:
using System;
using System.Windows.Forms;
namespace kHSw
{
public class Startup
{
public Startup()
{
}
[STAThread]
static void Main()
{
if (AppIsAlreadyRunning)
{
Application.Exit();
}
else
{
Application.Run(new MainForm()); // Where MainForm is the name of the form to load
}
}

[DllImport("user32.dll", EntryPoint="SetForegroundWindow")]
static extern IntPtr SetForegroundWindow(IntPtr hWnd);

private bool AppIsAlreadyRunning()
{
Process c = Process.GetCurrentProcess();
foreach (Process p in Process.GetProcessesByName(c.ProcessName))
{
if (p.Id != c.Id)
{
if (p.MainModule.FileName.ToLower().Equals(c.MainModule.FileName.ToLower()))
{
SetForegroundWindow(p.MainWindowHandle);
return true;
}
}
}
return false;
}
}
}

And here's the same functionality in VB.NET:
Imports System.Runtime.InteropServices
Public Class Startup
<STAThread()> _
Public Shared Sub Main()
If AppIsAlreadyRunning() Then
Application.Exit()
Else
Application.Run(New MainForm) 'Where MainForm is the name of the form to load
End If
End Sub

<DllImport("user32.dll", EntryPoint:="SetForegroundWindow")> _
Shared Function SetForegroundWindow(ByVal hwnd As IntPtr) As IntPtr
End Function

Public Shared Function AppIsAlreadyRunning() As Boolean
Dim c As Process = Process.GetCurrentProcess()
For Each p As Process In Process.GetProcessesByName(c.ProcessName)
If p.Id <> c.Id Then
If p.MainModule.FileName.ToLower.Equals(c.MainModule.FileName.ToLower) Then
SetForegroundWindow(p.MainWindowHandle)
Return True
End If
End If
Next
Return False
End Function
End Class

Nice, more then 25 lines of code where it only took 1 line in VB6...

0 Comments:

Post a Comment

<< Home


 
Stefanie Worm is het liefste vrouwtje van de wereld.
Melina is de liefste schatsie van de wereld (Erik De Maeyer).