Running another exec file

  • Thread starter Thread starter No One
  • Start date Start date
N

No One

I have a C# programme that needs to run some of Windows executable
files. I first need to check if that programme is already running, and
if it is, simply bring the window to the front. How can I search for a
Window handle of an execute file?
 
You'd have to resort to Win32 API calls.

At the least, you need to know your "other" application's window title. If
you do, you can do a FindWindow (...) to get a handle to the window and
SetForegroundWindow () to bring it to front.

However, this method is in no way fool-proof. Someone else can come by and
set their window's title to match your "other" app's window title and you'll
be stuck forever not able to execute your "other" app.

Or, your "other" app might be in starting up phase and its window has not
been created yet. FindWindow will fail and your app will happily go ahead
and launch it again; you'll end up with two instances.

One clean way to solve this problem is make your "other" app inherently
singleton. You can use named kernel objects to solve the problem (mutex,
event, etc).

HTH

-vJ
 
Check out System.Diagnostics.Process. In particular, the GetProcessesByName
method and the MainWindowHandle property.
 
General approach is: In application we should create any named kernel object
(for example Mutex),
then we can access to it from any windows apps by name. Moreover we can
define is object created early or in current function.
And if it is new instance of Mutex, so application already running and vice
versa.
In .NET Win32 Mutex represented by System.Threading.Mutex namespace.
Example:

class MyApplication
{
public static void Main()
{
if ( InstanceExists() )
{
return;
}
Console.WriteLine( "Application is running: Press enter to exit" );
Console.ReadLine();
}

static Mutex mutex;
static bool InstanceExists()
{
bool createdNew;
mutex = new Mutex( false, "My Mutex Name", out createdNew );
return !createdNew;
}
}
 
Back
Top