.net2005,用互斥来控制,程序只启动一次的一点经验(万恶的"release")

首先我的代码如下:

bool  isExist;
Mutex MyMutex 
=   new  Mutex( true , " MySoft " , out  isExist);
if  (isExist)
{
  
//程序运行
  Application.Run(new MainForm());
}

else
{
  
//show ErrorMessage Application terminate
}


好好的代码在"debug"模式下正常运行,呵呵,运行的挺美~
要发布了,把配置改为"release",把生成中的调试信息改为"none"(.net2003的发布根本不用改)

结果:哇!~互斥不起做用了,把"release"模式下的调试信息改为"full",互斥有起作用了,不知道为什么,

但是觉得平白多个pdb文件,很不舒服~

最后从网上找了点资料整理出来,贡献出来:

 

using  System.Diagnostics;
using  System.Reflection;
using  System.Runtime.InteropServices;

    
private   const   int  WS_SHOWNORMAL  =   1 ;
  [DllImport(
" User32.dll " )]
  
private   static   extern   bool  ShowWindowAsync(IntPtr hWnd,  int  cmdShow);
  [DllImport(
" User32.dll " )]
  
private   static   extern   bool  SetForegroundWindow(IntPtr hWnd);

    
    
public   static  Process RunningInstance()
  
{
    Process current 
= Process.GetCurrentProcess();
    Process[] processes 
= Process.GetProcessesByName(current.ProcessName);

    
//Loop through the running processes in with the same name
    foreach (Process process in processes)
    
{
      
//Ignore the current process
      if (process.Id != current.Id && Assembly.GetExecutingAssembly().Location.Replace("/""/"== current.MainModule.FileName)
        
return process;
    }
   
    
return null;
  }

  
public   static   bool  HandleRunningInstance(Process instance)
  
{
    instance.WaitForInputIdle();
    
//确保窗口没有被最小化或最大化
    ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
    
//设置真实例程为foreground window
    return SetForegroundWindow(instance.MainWindowHandle);
  }
 
  
  [STAThread]
  
static   void  Main( string [] args)
    
{
        Process MYSoft 
= RunningInstance();
        
if(MYSoft ==null)
        
{
             
//启动程序
        }

        
else
        
{
            
//激活已启动的程序
            HandleRunningInstance(MYSoft);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值