469,356 Members | 2,013 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,356 developers. It's quick & easy.

How to limit program can only run one instance.

Hi All,

How to limit the c# program can only run one instance at the same
time ?

Thank you!

Best regards,
Boki.

Jul 23 '07 #1
20 10296
"Boki Digtal" <bo******@ms21.hinet.netwrote in message news:11*********************@x35g2000prf.googlegro ups.com...
How to limit the c# program can only run one instance at the same
time ?

using System.Threading;

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup is...
}
}
--
Mark Rae
ASP.NET MVP
http://www.markrae.net
Jul 23 '07 #2
On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
"Boki Digtal" <bokit...@ms21.hinet.netwrote in messagenews:11*********************@x35g2000prf.go oglegroups.com...
How to limit the c# program can only run one instance at the same
time ?

using System.Threading;

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup is...
}

}

--
Mark Rae
ASP.NET MVPhttp://www.markrae.net
Great, thanks!

Boki.

Jul 24 '07 #3
On 7 24 , 2 27 , Boki Digtal <bokit...@ms21.hinet.netwrote:
On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
"Boki Digtal" <bokit...@ms21.hinet.netwrote in messagenews:11*********************@x35g2000prf.go oglegroups.com...
How to limit the c# program can only run one instance at the same
time ?
using System.Threading;
bool blnFirstInstance;
using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup is...
}
}
--
Mark Rae
ASP.NET MVPhttp://www.markrae.net

Great, thanks!

Boki.
Is there any easier way like OnlyOneInstance = ture;

Thanks :)

Boki.

Jul 30 '07 #4
"Boki Digtal" <bo******@ms21.hinet.netwrote in message
news:11*********************@i38g2000prf.googlegro ups.com...
using System.Threading;
bool blnFirstInstance;
using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out
blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use
Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup
is...
}
}

Great, thanks!

Is there any easier way like OnlyOneInstance = ture;
An easier way? The above is only a dozen lines of code...

Can't you get it to work, then...?
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jul 30 '07 #5
On 7 30 , 1 51 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
"Boki Digtal" <bokit...@ms21.hinet.netwrote in message

news:11*********************@i38g2000prf.googlegro ups.com...
using System.Threading;
bool blnFirstInstance;
using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out
blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use
Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup
is...
}
}
Great, thanks!
Is there any easier way like OnlyOneInstance = ture;

An easier way? The above is only a dozen lines of code...

Can't you get it to work, then...?

--
Mark Rae
ASP.NET MVPhttp://www.markrae.net
Sorry, in fact, I don't have try it yet.

If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.

I believe your code can work, but I am just curious if there is any
other methods.

:)

Thanks!

Best regards,
Boki.

Jul 30 '07 #6
On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21.hinet.netwrote:
Sorry, in fact, I don't have try it yet.

If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.

I believe your code can work, but I am just curious if there is any
other methods.
You could add a reference to the Microsoft.VisualBasic assembly and
use the WindowsFormsApplicationBase class which I believe has this
sort of functionality. I don't know much about it, but it *might* make
things easier for you.

Jon

Jul 30 '07 #7
On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21.hinet.netwrote:
Sorry, in fact, I don't have try it yet.
If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.
I believe your code can work, but I am just curious if there is any
other methods.

You could add a reference to the Microsoft.VisualBasic assembly and
use the WindowsFormsApplicationBase class which I believe has this
sort of functionality. I don't know much about it, but it *might* make
things easier for you.

Jon
visual basic ... ? but I am using c# ...

Boki.

Jul 30 '07 #8
"Boki Digtal" <bo******@ms21.hinet.netwrote in message
news:11**********************@j4g2000prf.googlegro ups.com...
On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
>On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21.hinet.netwrote:
Sorry, in fact, I don't have try it yet.
If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.
I believe your code can work, but I am just curious if there is any
other methods.

You could add a reference to the Microsoft.VisualBasic assembly and
use the WindowsFormsApplicationBase class which I believe has this
sort of functionality. I don't know much about it, but it *might* make
things easier for you.

Jon

visual basic ... ? but I am using c# ...
Yes, but you can set a reference to the Microsoft.VisualBasic assembly and
use the (without wishing to get into a language war) "hand-holding"
functions ported over from VB6 if the code I suggested (which I pretty much
nicked from Jon anyway) is too much for you...
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jul 30 '07 #9
On 7 30 , 4 18 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
"Boki Digtal" <bokit...@ms21.hinet.netwrote in message

news:11**********************@j4g2000prf.googlegro ups.com...
On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21.hinet.netwrote:
Sorry, in fact, I don't have try it yet.
If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.
I believe your code can work, but I am just curious if there is any
other methods.
You could add a reference to the Microsoft.VisualBasic assembly and
use the WindowsFormsApplicationBase class which I believe has this
sort of functionality. I don't know much about it, but it *might* make
things easier for you.
Jon
visual basic ... ? but I am using c# ...

Yes, but you can set a reference to the Microsoft.VisualBasic assembly and
use the (without wishing to get into a language war) "hand-holding"
functions ported over from VB6 if the code I suggested (which I pretty much
nicked from Jon anyway) is too much for you...

--
Mark Rae
ASP.NET MVPhttp://www.markrae.net
OK, got it, thanks :)

Boki.

Jul 30 '07 #10
Try this

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.IO;

namespace SingleInstance
{
/// <summary>
/// Summary description for SingleApp.
/// </summary>
public class SingleApplication
{
public SingleApplication()
{

}
/// <summary>
/// Imports
/// </summary>

[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hWnd, int
nCmdShow);

[DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr
hWnd);

[DllImport("user32.dll")]
private static extern int IsIconic(IntPtr hWnd);

/// <summary>
/// GetCurrentInstanceWindowHandle
/// </summary>
/// <returns></returns>
private static IntPtr GetCurrentInstanceWindowHandle()
{
IntPtr hWnd = IntPtr.Zero;
Process process = Process.GetCurrentProcess();
Process[] processes =
Process.GetProcessesByName(process.ProcessName);
foreach(Process _process in processes)
{
// Get the first instance that is not
this instance, has the
// same process name and was started
from the same file name
// and location. Also check that the
process has a valid
// window handle in this session to
filter out other user's
// processes.
if (_process.Id != process.Id &&
_process.MainModule.FileName
== process.MainModule.FileName &&
_process.MainWindowHandle !=
IntPtr.Zero)
{
hWnd =
_process.MainWindowHandle;
break;
}
}
return hWnd;
}
/// <summary>
/// SwitchToCurrentInstance
/// </summary>
private static void SwitchToCurrentInstance()
{
IntPtr hWnd =
GetCurrentInstanceWindowHandle();
if (hWnd != IntPtr.Zero)
{
// Restore window if minimised. Do not
restore if already in
// normal or maximised window state,
since we don't want to
// change the current state of the
window.
if (IsIconic(hWnd) != 0)
{
ShowWindow(hWnd, SW_RESTORE);
}

// Set foreground window.
SetForegroundWindow(hWnd);
}
}

/// <summary>
/// Execute a form base application if another
instance already running on
/// the system activate previous one
/// </summary>
/// <param name="frmMain">main form</param>
/// <returns>true if no previous instance is
running</returns>
public static bool Run(System.Windows.Forms.Form
frmMain)
{
if(IsAlreadyRunning())
{
//set focus on previously running app
SwitchToCurrentInstance();
return false;
}
Application.Run(frmMain);
return true;
}

/// <summary>
/// for console base application
/// </summary>
/// <returns></returns>
public static bool Run()
{
if(IsAlreadyRunning())
{
return false;
}
return true;
}

/// <summary>
/// check if given exe alread running or not
/// </summary>
/// <returns>returns true if already running</returns>
private static bool IsAlreadyRunning()
{
string strLoc =
Assembly.GetExecutingAssembly().Location;
FileSystemInfo fileInfo = new
FileInfo(strLoc);
string sExeName = fileInfo.Name;
bool bCreatedNew;

mutex = new Mutex(true, "Global\\"+sExeName,
out bCreatedNew);
if (bCreatedNew)
mutex.ReleaseMutex();

return !bCreatedNew;
}

static Mutex mutex;
const int SW_RESTORE = 9;
}
}

IN PROGRAM.CS add line
SingleApplication.Run(new frmMain());
On Mon, 30 Jul 2007 01:29:28 -0700, Boki Digtal
<bo******@ms21.hinet.netwrote:
>On 7 30 , 4 18 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
>"Boki Digtal" <bokit...@ms21.hinet.netwrote in message

news:11**********************@j4g2000prf.googlegr oups.com...
On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21.hinet.netwrote:
Sorry, in fact, I don't have try it yet.
If I recall correctly, there is a setting in VC6, when we assign so
many parameters to create a form. For this purpose, what we need to do
is assign a parameter as true only.
I believe your code can work, but I am just curious if there is any
other methods.
>You could add a reference to the Microsoft.VisualBasic assembly and
use the WindowsFormsApplicationBase class which I believe has this
sort of functionality. I don't know much about it, but it *might* make
things easier for you.
>Jon
visual basic ... ? but I am using c# ...

Yes, but you can set a reference to the Microsoft.VisualBasic assembly and
use the (without wishing to get into a language war) "hand-holding"
functions ported over from VB6 if the code I suggested (which I pretty much
nicked from Jon anyway) is too much for you...

--
Mark Rae
ASP.NET MVPhttp://www.markrae.net

OK, got it, thanks :)

Boki.
Jul 31 '07 #11
"Ivica Muruzovic" <kv**@eunet.yuwrote in message
news:ai********************************@4ax.com...
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
There really is no need to use WinAPI for this...
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jul 31 '07 #12
On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPAMrae.netwrote:
"Boki Digtal" <bokit...@ms21.hinet.netwrote in messagenews:11*********************@x35g2000prf.go oglegroups.com...
How to limit the c# program can only run one instance at the same
time ?

using System.Threading;

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstance))
{
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single Use Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1()); // or whatever your startup is...
}

}

--
Mark Rae
ASP.NET MVPhttp://www.markrae.net
Hi,
Please see my complete "Program.cs" below:
After I did this, it can still run more than one instance.

/////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace Ring_Buffer_Test
{

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{

bool blnFirstInstance;
using (Mutex objMutex = new Mutex(false,"Local\\" +
"BokiTesting", out blnFirstInstance))

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
if (!blnFirstInstance)
{
MessageBox.Show("<app nameis already running", "Single
Use Only", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}
else
{
Application.Run(new Form1());
}

}
}
}
////////////////
I don't know why ...

Boki.

Aug 2 '07 #13
Boki <bo**********@gmail.comwrote:
Please see my complete "Program.cs" below:
After I did this, it can still run more than one instance.
Yes, because your "using" statement for the mutex doesn't have braces
round the code. You've effectively got:

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false,"Local\\" + "BokiTesting",
out blnFirstInstance))
{
Application.EnableVisualStyles();
}

Application.SetCompatibleTextRenderingDefault(fals e);

// Rest of code...

The idea is to hold the mutex for the whole of the time your app is
running.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 2 '07 #14
On 8 2 , 2 22 , Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Boki <boki.digi...@gmail.comwrote:
Please see my complete "Program.cs" below:
After I did this, it can still run more than one instance.

Yes, because your "using" statement for the mutex doesn't have braces
round the code. You've effectively got:

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false,"Local\\" + "BokiTesting",
out blnFirstInstance))
{
Application.EnableVisualStyles();

}

Application.SetCompatibleTextRenderingDefault(fals e);

// Rest of code...

The idea is to hold the mutex for the whole of the time your app is
running.

--
Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Yes, you are right, thanks!

Boki.

Aug 2 '07 #15
On Aug 2, 2:22 pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Boki <boki.digi...@gmail.comwrote:
Please see my complete "Program.cs" below:
After I did this, it can still run more than one instance.

Yes, because your "using" statement for the mutex doesn't have braces
round the code. You've effectively got:

bool blnFirstInstance;

using (Mutex objMutex = new Mutex(false,"Local\\" + "BokiTesting",
out blnFirstInstance))
{
Application.EnableVisualStyles();

}

Application.SetCompatibleTextRenderingDefault(fals e);

// Rest of code...

The idea is to hold the mutex for the whole of the time your app is
running.

--
Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Hello,

I tried same code on Vista, it seems no work. but works on XP.

Boki.

Aug 5 '07 #16
Boki <bo**********@gmail.comwrote:
I tried same code on Vista, it seems no work. but works on XP.
Could you post a short but complete program which demonstrates the
problem on Vista?

(You haven't shown us Form1, for example.)

It should work fine on Vista.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 5 '07 #17
On 8 6 , 5 27 , Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Boki <boki.digi...@gmail.comwrote:
I tried same code on Vista, it seems no work. but works on XP.

Could you post a short but complete program which demonstrates the
problem on Vista?

(You haven't shown us Form1, for example.)

It should work fine on Vista.

--
Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Hi

I am using the same code here for program.cs as below:

////////////////
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]

static void Main()
{
bool firstInstance;
Mutex mutex = new Mutex(false, "Local\\" + "SPECIAL TEST
8324428", out firstInstance);

if (firstInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
Application.Run(new Form1());
}
else
{
MessageBox.Show("An instance has already been
run!","BOKI BOKI");
}

}
///////////////

However, the form1 is a normal form. I run the same .exe flie on XP,
it works well, I can see the message box.

When I copy the same .exe file on Vista environment, wow, it can has
many instances, I can't see any message box on Vista.

Boki.

Aug 6 '07 #18
Boki <bo**********@gmail.comwrote:
I am using the same code here for program.cs as below:

////////////////
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]

static void Main()
{
bool firstInstance;
Mutex mutex = new Mutex(false, "Local\\" + "SPECIAL TEST
8324428", out firstInstance);

if (firstInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
Application.Run(new Form1());
}
else
{
MessageBox.Show("An instance has already been
run!","BOKI BOKI");
}

}
///////////////
Again, that's *not* the code we suggested - and won't always work on
XP.

You *do* want a using statement for "mutex", but covering the whole of
the rest of the code.

Look back at my reply from August 2nd.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 6 '07 #19
On 31 jul, 08:11, Ivica Muruzovic <k...@eunet.yuwrote:
Process[] processes =
Process.GetProcessesByName(process.ProcessName);
I think your process will need administrator privileges to be able to
do this... So I would advise against this mechanism.

Kristof Verbiest
http://kristofverbiest.blogspot.com/

Aug 7 '07 #20
There is another reason to avoid this... sometimes the process name
isn't what you think it is... for instance, 1.1 "zero touch"
deployments (over the web) run in a hosting shell process - which
means that your app would refuse to work if anything else (unrelated)
was being hosted in the same way.

I'd stick with a named mutex myself...

Marc
Aug 7 '07 #21

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.