The following code demonstrates how to detect if there is an instance of your application already running. If detected, it will bring that application to the foreground (restoring its window state if iconic), and then terminating the current application. This is useful in instances where you want to ensure that only one instance of your application is running.
This code was put together using the prior work of Taylor Wood ("Window Hiding in C#") and a message in the C# forum posted by David Wengier illustrating the use of the Process class. Without their help, this would have taken me several hours to put together, instead of a few minutes!
using System; using System.Diagnostics; using System.Runtime.InteropServices; class AppMain { ; static void Main() { // get the name of our process string proc=Process.GetCurrentProcess().ProcessName; // get the list of all processes by that name Process[] processes=Process.GetProcessesByName(proc); // if there is more than one process... if (processes.Length > 1) { // Assume there is our process, which we will terminate, // and the other process, which we want to bring to the // foreground. This assumes there are only two processes // in the processes array, and we need to find out which // one is NOT us. // get our process Process p=Process.GetCurrentProcess(); int n=0; // assume the other process is at index 0 // if this process id is OUR process ID... if (processes[0].Id==p.Id) { // then the other process is at index 1 n=1; } // get the window handle IntPtr hWnd=processes[n].MainWindowHandle; // if iconic, we need to restore the window if (IsIconic(hWnd)) { ShowWindowAsync(hWnd, SW_RESTORE); } // bring it to the foreground SetForegroundWindow(hWnd); // exit our process return; } // ... continue with your application initialization here. } }
This code is a great example of interfacing with Win32 libraries and using some esoteric functions in .NET.
General
News
Question
Answer
Joke
Rant
Admin