C#FORM只允许启动一个进程

 

SingleInstance类

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;// win API 引用
using System.Diagnostics;//Process

namespace QueuerServer
ExpandedBlockStart.gifContractedBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// 使应用程序仅运行一个实例。
    
/// </summary>

    static class SingleInstance
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        [DllImport(
"User32.dll")]
        
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport(
"User32.dll")]
        
private static extern bool SetForegroundWindow(IntPtr hWnd);

        
private static Mutex mutex = null;

        
public static bool CreateMutex()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return CreateMutex(Assembly.GetEntryAssembly().FullName);
        }


        
public static bool CreateMutex(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
bool result = false;
            mutex 
= new Mutex(true, name, out result);
            
return result;
        }


        
public static void ReleaseMutex()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (mutex != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                mutex.Close();
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// ShowWindow() Commands
        
/// </summary>

        private const int SW_HIDE = 0;
        
private const int SW_SHOWNORMAL = 1;
        
private const int SW_NORMAL = 1;
        
private const int SW_SHOWMINIMIZED = 2;
        
private const int SW_SHOWMAXIMIZED = 3;
        
private const int SW_MAXIMIZE = 3;
        
private const int SW_SHOWNOACTIVATE = 4;
        
private const int SW_SHOW = 5;
        
private const int SW_MINIMIZE = 6;
        
private const int SW_SHOWMINNOACTIVE = 7;
        
private const int SW_SHOWNA = 8;
        
private const int SW_RESTORE = 9;
        
private const int SW_SHOWDEFAULT = 10;
        
private const int SW_FORCEMINIMIZE = 11;
        
private const int SW_MAX = 11;

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 激活同Instance窗体
        
/// </summary>
        
/// <param name="instance"></param>
        
/// <returns></returns>

        public static bool HandleRunningInstance(Process instance)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//确保窗口没有被最小化或最大化 
            ShowWindowAsync(instance.MainWindowHandle, SW_MAXIMIZE);
            
//设置为foreground window 
            return SetForegroundWindow(instance.MainWindowHandle);
        }


        
public static bool HandleRunningInstance()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Process p 
= GetRunningInstance();
            
if (p != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                HandleRunningInstance(p);
                
return true;
            }

            
return false;
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 获取应用程序进程实例,如果没有匹配进程,返回Null值
        
/// </summary>
        
/// <returns></returns>

        public static Process GetRunningInstance()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Process currentProcess 
= Process.GetCurrentProcess(); //获取当前进程
            
//获取当前运行程序完全限定名 
            string currentFileName = currentProcess.MainModule.FileName;
            
//获取进程名为ProcessName的Process数组。 
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            
//遍历有相同进程名称正在运行的进程 
            foreach (Process process in processes)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if (process.MainModule.FileName == currentFileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
if (process.Id != currentProcess.Id) //根据进程ID排除当前进程 
                        return process;//返回已运行的进程实例 
                }

            }

            
return null;
        }

    }

}


主工程中:

 

ContractedBlock.gif ExpandedBlockStart.gif Program
namespace QueuerServer
ExpandedBlockStart.gifContractedBlock.gif
{
    
static class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
private static MainForm m_MainForm;
        
public static MainForm MainForm
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get return Program.m_MainForm; }
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ContractedSubBlock.gifExpandedSubBlockStart.gif            
#region
            
bool autoStart = false;
            
bool hide = false;
            
bool service = false;
            
foreach (string arg in args)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//MessageBox.Show(arg);
                string command = arg.Trim().ToLower();
                
//if(arg.Trim().ToLower().Equals("-autostart"))
                switch (command)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
case "-autostart":
                        autoStart 
= true;
                        
break;
                    
case "-hide":
                        hide 
= true;
                        
break;
                    
case "-service":
                        service 
= true;
                        
break;
                    
default:
                        
break;
                }

            }

            
#endregion


            
//使应用程序只能生成一个进程
            if (SingleInstance.CreateMutex())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(
false);

                RunMainForm(autoStart, hide, service);
                SingleInstance.ReleaseMutex();
            }

            
else//若已经运行了一个进程,则激活该进程。
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                
//MessageBox.Show("程序已经运行!");
                SingleInstance.HandleRunningInstance();
            }


            
//Application.EnableVisualStyles();
            
//Application.SetCompatibleTextRenderingDefault(false);
            
//Application.Run(new MainForm(autoStart, hide, service));
        }



        
private static void RunMainForm(bool autoStart, bool hide, bool service)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                CreateMainForm(autoStart, hide, service);
            }

            
catch (Exception e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if (DialogResult.OK == MessageBox.Show(e.Message, "应用程序错误", MessageBoxButtons.OKCancel))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
//这是一个重新启动机制,但是丢失全部应用程序信息。
                    RunMainForm(autoStart, hide, service);
                }

                
//XMLMessageManager.WriteExceptionToLog(e);
            }

        }


        
private static void CreateMainForm(bool autoStart, bool hide, bool service)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (m_MainForm != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                m_MainForm.Dispose();
                m_MainForm 
= null;
            }

            m_MainForm 
= new MainForm(autoStart, hide, service);
            Application.Run(m_MainForm);
        }

    }

}

转载于:https://www.cnblogs.com/xinyuxin912/archive/2008/11/11/1331288.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值