Bringing a form to focus

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
 
C

Chris Marchal[MSFT]

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.
 
M

Muscha

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top