There are ways to do with few classes....
We can create a simple class to postmessage and related stuffs as :
static public class WinApi
{
[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);
public static int RegisterWindowMessage(string format, params object[] args)
{
string message = String.Format(format, args);
return RegisterWindowMessage(message);
}
public const int HWND_BROADCAST = 0xffff;
public const int SW_SHOWNORMAL = 1;
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImportAttribute("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImportAttribute("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public static void ShowToFront(IntPtr window)
{
ShowWindow(window, SW_SHOWNORMAL);
SetForegroundWindow(window);
}
}
The after we need create a class to determine instances using the PostMessage...
static public class SingleInstance
{
public static readonly int WM_SHOWFIRSTINSTANCE =
WinApi.RegisterWindowMessage("WM_SHOWFIRSTINSTANCE|{0}", ProgramInfo.AssemblyGuid);
static Mutex mutex;
static public bool Start()
{
bool onlyInstance = false;
string mutexName = String.Format("Local\\{0}", ProgramInfo.AssemblyGuid);
mutex = new Mutex(true, mutexName, out onlyInstance);
return onlyInstance;
}
static public void ShowFirstInstance()
{
WinApi.PostMessage(
(IntPtr)WinApi.HWND_BROADCAST,
WM_SHOWFIRSTINSTANCE,
IntPtr.Zero,
IntPtr.Zero);
}
static public void Stop()
{
mutex.ReleaseMutex();
}
}
Create a class that fetch app guid:
static public class ProgramInfo
{
static public string AssemblyGuid
{
get
{
object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
if (attributes.Length == 0)
{
return String.Empty;
}
return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value;
}
}
}
Now we can modify the entry point as :
[STAThread]
static void Main()
{
if (!SingleInstance.Start())
{
SingleInstance.ShowFirstInstance();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Form1 mainForm = new Form1();
Application.Run(mainForm);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
SingleInstance.Stop();
}
Now need to add few methods to Form1(the intitial form that run from entry point:
protected override void WndProc(ref Message message)
{
if (message.Msg == SingleInstance.WM_SHOWFIRSTINSTANCE)
{
ShowWindow();
}
base.WndProc(ref message);
}
public void ShowWindow()
{
WinApi.ShowToFront(this.Handle);
}