In case anyone is having the same issue, I want to clarify the steps.
First, you have to change what happens in program entry point. As others mentioned, the Main() function that acts as an entry point to WPF programs is auto-generated (App.g.i.cs); So we have to take control of it somehow. As mentioned in this answer, there are several ways to do so. Personally I prefer the Third Approach:
Include another class in your project that defines the Main method as below:
class Startup
{
[STAThread]
public static void Main()
{
// Your single instance control (shown in below code)
...
}
}
Identify the class whose main you want the application to use as entry point. This can be done via the project properties (right-click on your project >properties. or alt+enter while your project is selected in Solution Explorer). In the Application tab, modify the Startup object properties from the drop down:
Second, you have to decide for a mechanism to know if your program is being run more than once. There are several ways to do that (as the other answers mentioned). The one I prefer is this:
...
// Your single instance control:
bool firstInstance = true;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, "some_unique_name_that_only_your_project_will_use", out firstInstance);
if (firstInstance)
{
// Everything that needs to be done in main class, for example:
YourProject.App app = new YourProject.App();
app.InitializeComponent();
app.Run();
}
else
{
// Your procedure for additional instances of program
MessageBox.Show("Another instance of this application is already running.");
}
These two steps together are one of the easiest ways to achieve your goal, even before Caliburn.Micro
takes control of your program.