|
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
namespace SingleInstance
{
/// <summary>
/// Summary description for SingleApp.
/// </summary>
public class SingleApplication
{
private SingleApplication()
{
}
/// <summary>
/// Imports
/// </summary>
[DllImport("user32.Dll")]
private static extern int EnumWindows(EnumWinCallBack callBackFunc, int lParam);
[DllImport("User32.Dll")]
private static extern void GetWindowText(int hWnd, StringBuilder str, int nMaxCount);
[DllImport("user32.dll",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd,Int32 nCmdShow);
/// <summary>
/// EnumWindowCallBack
/// </summary>
/// <param name="hwnd"></param>
/// <param name="lParam"></param>
/// <returns></returns>
private static bool EnumWindowCallBack(int hwnd, int lParam)
{
windowHandle = (IntPtr)hwnd;
StringBuilder sbuilder = new StringBuilder(256);
GetWindowText((int)windowHandle, sbuilder, sbuilder.Capacity);
string strTitle = sbuilder.ToString();
if(strTitle == sTitle)
{
ShowWindow(windowHandle, SW_RESTORE);
SetForegroundWindow(windowHandle);
return false;
}
return true;
}//EnumWindowCallBack
/// <summary>
/// Execute a form base application if another instance already running on
/// the system activate previous one
/// </summary>
/// <param name="frmMain">main form</param>
/// <returns>true if no previous instance is running</returns>
public static bool Run(System.Windows.Forms.Form frmMain)
{
sTitle = frmMain.Text;
if( EnumWindows (new EnumWinCallBack(EnumWindowCallBack), 0) == 0)
{
return false;
}
Application.Run(frmMain);
return true;
}
public static bool Run(string frmText)
{
sTitle = frmText;
if( EnumWindows (new EnumWinCallBack(EnumWindowCallBack), 0) == 0)
{
return false;
}
return true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool Run()
{
Process pr = Process.GetCurrentProcess();
string strProcessName = pr.ProcessName;
if(System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
{
return false;
}
return true;
}
const int SW_RESTORE = 9;
static string sTitle;
static IntPtr windowHandle;
delegate bool EnumWinCallBack(int hwnd, int lParam);
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
I am an MCSD.NET and MCT. I give a lot of Microsoft Trainings (www.bdcworld.com) in France.