-----------------------------------------------------------
New Message on BDOTNET
-----------------------------------------------------------
From: saileshsaha
Message 3 in Discussion
Hi Mr
BabuRaj,
The following code shows how to make sure that
there is only one instance of your Windows Forms application running. The code
first searches for processes with the same name as the and if one is found it
makes sure that was ran from the same location. If it decides that there is
another instance running, it shows that main window of the other instance,
otherwise it runs another instance of the main form.
using System;
using
System.Runtime.InteropServices;
using System.Windows.Forms;
using
System.Diagnostics;
using System.Reflection;
public class
OneInstnace
{
[STAThread]
public static void
Main()
{
//Get the running instance.
Process instance
= RunningInstance();
if (instance == null)
{
//There
isn't another instance, show our form.
Application.Run (new
Form());
}
else
{
//There is another
instance of this
process.
HandleRunningInstance(instance);
}
}
public
static Process RunningInstance()
{
Process current =
Process.GetCurrentProcess();
Process[] processes =
Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same
name
foreach (Process process in
processes)
{
//Ignore the current process
if
(process.Id != current.Id)
{
//Make sure that the process is
running from the exe file.
if
(Assembly.GetExecutingAssembly().Location.Replace("/", "\\")
==
current.MainModule.FileName)
{
//Return the other
process instance.
return
process;
}
}
}
//No other instance was found, return
null.
return null;
}
public static void HandleRunningInstance(Process
instance)
{
//Make sure the window is not minimized or
maximized
ShowWindowAsync (instance.MainWindowHandle ,
WS_SHOWNORMAL);
//Set the real intance to foreground
window
SetForegroundWindow
(instance.MainWindowHandle);
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(
IntPtr
hWnd, int cmdShow);
[DllImport("User32.dll")] private static extern
bool
SetForegroundWindow(IntPtr hWnd);
private const int
WS_SHOWNORMAL = 1;
}
Thanks and
Regards,
Sailesh
-----------------------------------------------------------
To stop getting this e-mail, or change how often it arrives, go to your E-mail
Settings.
http://groups.msn.com/BDotNet/_emailsettings.msnw
Need help? If you've forgotten your password, please go to Passport Member Services.
http://groups.msn.com/_passportredir.msnw?ppmprop=help
For other questions or feedback, go to our Contact Us page.
http://groups.msn.com/contact
If you do not want to receive future e-mail from this MSN group, or if you received
this message by mistake, please click the "Remove" link below. On the pre-addressed
e-mail message that opens, simply click "Send". Your e-mail address will be deleted
from this group's mailing list.
mailto:[EMAIL PROTECTED]