您的位置:首页 > 其它

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

2006-07-27 11:00 465 查看
首先我的代码如下:


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);


}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐