473,499 Members | 1,593 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 10593
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2612
by: Bloon | last post by:
I have a question that how to debug a program only having .exe file. Is there any techniques or tools that can do that? Thanks a lot.
4
1940
by: grocery_stocker | last post by:
#include <iostream> //for cin and cout #include <iomanip> // for setw() #include <string> // for strlen() strcmp() strrev() #include <fstream> //ifstream and ofstream: file (input & output)...
3
3463
by: Vikrant | last post by:
Friends, Due an application (old) install program problem, Under AIX I could only create DB2 instance, I could also catalog it. Its complex application and I am not expert in creating full...
4
7071
by: Josh Burkard | last post by:
Hello How can i control, that a user can't start my VB.Net-Program 2 ore more times at once (maybee like Outlook)? At same time Parameters which are transfered with the second program should be...
1
2807
by: Shisou | last post by:
I think the title says it all... i'm building a program that will read in a dictionary and then ask the user for a string and will check all permutations of the string against the dictionary to see...
0
7132
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7390
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4602
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3103
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
302
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.