實現同時只允許運行一個程序實例

方法一:

/// <summary>
/// 從這裏開始運行
/// </summary>
[STAThread]
static void Main()
{
    Process instance = RunningInstance();
    if (instance == null)
    {
        //沒有實例在運行
        WeatherApp appInstance = new WeatherApp();
        appInstance.StartMainGui();
    }
    else
    {
        //已經有一個實例在運行
        HandleRunningInstance(instance);
    }
}
#region 確保只有一個實例
public static Process RunningInstance()
{
    Process current = Process.GetCurrentProcess();
    Process[] processes = Process.GetProcessesByName(current.ProcessName);
    //遍歷與當前進程名稱相同的進程列表
    foreach (Process process in processes)
    {
        //Ignore the current process
        if (process.Id != current.Id)
        {
            //Make sure that the process is running from the exe file.
            if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
            {
                //Return the other process instance.
                return process;
            }
        }
    }
    return null;
}
private static void HandleRunningInstance(Process instance)
{
    MessageBox.Show("該應用系統已經在運行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
    ShowWindowAsync(instance.MainWindowHandle, 1); //調用api函數,正常顯示窗口
    SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端。
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
#endregion
 

方法二:

[STAThread]
static void Main(string[] args)
{
    bool isFirst;

    System.Threading.Mutex mutex = new System.Threading.Mutex(true, "WindowAppTest", out isFirst);
    //這裏的myApp是程序的標識,建議換成你的程序的物理路徑,這樣的話如果在一個操作系統中這個標誌不會和其它程序衝突
    if (!isFirst)
    {
        MessageBox.Show("Exist");
        Environment.Exit(1);//實例已經存在,退出程序
    }
    else
    {
        Application.Run(new Form1());
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章