Hi
I created a C# sharp application and it has no threads. I want prevent someone executing the same application if it is currently executing.
Thanks
Reginold
Printable View
Hi
I created a C# sharp application and it has no threads. I want prevent someone executing the same application if it is currently executing.
Thanks
Reginold
Use this code in your Main() function:
static void Main()
{
string procName = Application.ProductName;
System.Diagnostics.Process[] myProcesses
= System.Diagnostics.Process.GetProcessesByName(procName);
if (myProcesses.Length > 1)
{
MessageBox.Show("Application Already Open");
return;
}
// Now start the application
Application.Run(new Form1());
}
if your app has no threads, thats pretty much going to guarantee that no one will be able to use it, because any running app is going to be on *some* thread.Quote:
Originally Posted by rchrishantha
Here is another idea:
The next section will close the PREVIOUS instance of the application:Code:using System.Threading
using System.Runtime.InteropServices;
public class Form1 : Form
{
[STAThread]
static void Main()
{
bool createdNew;
Mutex m = new Mutex(true, "YourAppName", out createdNew);
if (! createdNew)
{
// app is already running...
MessageBox.Show("Only one instance of this application is allowed at a time.");
return;
}
Application.Run(new Form1());
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}
}
Code:using System;
using System.ComponentModel;
using System.Diagnostics;
static void Main()
{
// get the name of the current process
Process currentProcess = Process.GetCurrentProcess();
string currProcessName = currentProcess.ProcessName;
// get all instances of the this application
Process[] prevAppInstance = Process.GetProcessesByName(currProcessName);
// kill all other instances of this application
for(int i = 0 ; i<prevAppInstance.GetLength(0) ; i++)
{
if(prevAppInstance[i].Id != currentProcess.Id)
{
prevAppInstance[i].Kill();
}
}
// run the aplication
Application.Run(new Form1());
}
or this one,Code:static void Main()
Int32 isProcessRunning;
isProcessRunning = System.Diagnostics.Process.GetProcessesByName(
System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length;
if(isProcessRunning != 1)
{
MessageBox.Show("Already an Instance running");
}
else
{
Application.Run(new Form1());
}
rofl..Quote:
Originally Posted by MadHatter