How to Make my programn run for once in C#?

  • Thread starter Thread starter ygy
  • Start date Start date
Y

ygy

I want my programn run for once.Forbid the programn run when the
programn has run.I know I can use CWnd::FindWindow() funtion in
C++(MFC).What should I do in C#.Thank you!
 
Hi,

You can take the same approach in c# through P/Invoke layer. You can call to
the FindWindow() fucntion.

If you need a pure c# solution use System.Diagnostic.Process...

static void Main()

{

// get the name of our process

string proc=Process.GetCurrentProcess().ProcessName;

// get the list of all processes by that name

Process[] processes=Process.GetProcessesByName(proc);

// if there is more than one process...

if (processes.Length > 1)

{

MessageBox.Show("Application is already running");

return;

} else

Application.Run(new Form1());

}

Regards,

Nirosh.
 
ygy said:
I want my programn run for once.Forbid the programn run when the
programn has run.I know I can use CWnd::FindWindow() funtion in
C++(MFC).What should I do in C#.Thank you!

It was nice and easy in VB with App.PrevInstance, wasn't it...? :-)

I use a Mutex for this in C#...

System.Threading.Mutex objMutex = null;
this.Visible = false;
// check there isn't already an instance of this app
running ------------------------------------------
try
{
bool blnCreatedMutex;
objMutex = new System.Threading.Mutex(true, "<MyAppName>", out
blnCreatedMutex);
if (!blnCreatedMutex)
{
MessageBox.Show("<MyAppName> is already running", "<MyAppName>",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
this.Close();
return;
}
else
{
GC.KeepAlive(objMutex);
this.Visible = true;
}
}
catch (Exception ex)
{
// do your error handling here
return;
}
 
Back
Top