c pound

I reject your reality and substitute my own!
posts - 46, comments - 37, trackbacks - 40

My Links

News

Archives

Image Galleries

Blog Communities

Blog is a stupid word

Lunch Hour

Resources

Single-Instance... the easy way

You want only one instance of your program to run at a time? Easy. If you are feeling particularly adventurous, I'm sure you could even figure out a simple way to switch to the currently running instance when someone tries to start a new one.

using System;
using System.Windows.Forms;
using System.Diagnostics;

namespace
Sample.SingleInstance
{
    static class Program
    {
        [
STAThread]
        static void Main()
        {
            //ensure that only one instance of this process can run at a time
            Process curProc = Process.GetCurrentProcess();
            if(Process.GetProcessesByName(curProc.ProcessName).Length <= 1)
            {
                Application.EnableVisualStyles();
                Application.Run(new frmMain());
            }
        }
    }
}

Print | posted on Friday, November 18, 2005 7:50 AM |

Feedback

Gravatar

# re: Single-Instance... the easy way

Get the main window handle from that other process, and post a message to it. The other instance of the app should be listening for messages that match the one your sending and activate itself or do whatever you want.

Otherwise, you could post WM_ACTIVATE (i think) to the window handle and the other instance wouldn't need to listen
11/18/2005 7:53 AM | Eric Pearson
Gravatar

# re: Single-Instance... the easy way

That is true... however, you may not want to activate the main window of the other instance. What if the other instance is in the middle of something where the user should not have access to the main window for some reason. What you really need to do is externally activate the *active* window of the other instance. This is, of course, more problematic but I would bet that there is a slick .Net way around this.
11/18/2005 8:02 AM | Dan Koster
Gravatar

# re: Single-Instance... the easy way

Thanks, works great!
12/20/2005 5:15 AM | Jonathan
Gravatar

# re: Single-Instance... the easy way

You can do this with a mutex too, and it probably performs much better than enumerating the processes.
12/20/2005 1:05 PM | Anthony Trudeau
Gravatar

# re: Single-Instance... the easy way

How, pray tell? Don't just leave us hanging like that. ;) Could you post a code snippet?
12/20/2005 1:10 PM | Dan Koster
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: