Bringing a form to focus

  • Thread starter Thread starter Muscha
  • Start date Start date
M

Muscha

Hello,

I have a launcher for a Windows Form application that will guard against
starting an already started application like the following:

private static Mutex singletonMutex;
static void Main(string[] args)
{
bool first;
singletonMutex = new Mutex(true, "MyApplication", out first);
if (first)
{
// process application startup
DoStartup(args);
}
else
{
MessageBox.Show("Application already running"); // YUCK!
}
}

Now the question is: How do I avoid using a message box instead bringing the
already started application to focus?

Thanks for any help.

/m
 
You could store the handle (window handle in the Platform SDK) for the
first application as part of the mutex name. When a second application is
started and you have checked your mutex, you can call SetForegroundWindow
with the handle of the first application's form.

I believe SetForegroundWindow needs to be called through P/Invoke in C#:

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

Chris Marchal
Microsoft UK Developer Support
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Chris,

How do you store this handle in the Mutex? Also it seems that
SetForegroundWindow only works if the form is in a normal state. How do I
both show the form if it's hidden and set it to a normal view ? Not minized.

Thanks,
 
Back
Top