這個問題是最近討論區朋友問到的問題,把它記錄在我的Blog裡,如下:
EXE執行檔已經運行了,如果我再去運行同樣EXE檔時,新的程序不再運行,而是將原來的EXE執行檔顯示在最前面,如果EXE執行檔是最小化的時候,先將它最大化後再顯示在最前面,outlook2003,迅雷、金山詞霸2009就是這樣的效果。
網路上有一個很好的解法,如下(C#):
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; namespace WindowsApplication3 { static class Program { [STAThread] static void Main() { //Get the running instance. Process instance = RunningInstance(); if (instance == null) { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.DoEvents(); //There isn't another instance, show our form. Application.Run(new Form1()); } else { //There is another instance of this process. HandleRunningInstance(instance); } } 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) { //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; } } } //No other instance was found, return null. return null; } public static void HandleRunningInstance(Process instance) { //Make sure the window is not minimized or maximized ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //Set the real intance to foreground window SetForegroundWindow(instance.MainWindowHandle); } [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); [DllImport("User32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); //1:normal //2:minimized //3:maximized private const int WS_SHOWNORMAL = 3; } }
參考網址:http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090213164530GII&fumcde=FUM20050124192253INM#BRD20090215180413HROhttp://www.cnblogs.com/ghostljj/archive/2007/10/02/912979.html
# re: [C#]EXE執行檔單獨運行小技巧, Posted by WL on 2009/3/30 上午 11:26 回覆
感謝大大的分享!!!我有個沿伸的問題想請教一下您的想法~~~我程式縮小時是直接收到右下角的系統列(notifyIcon),this.hide();如果我雙擊notifyIcon時,this.show();所以我在您程式中的HandleRunningInstance裡先找尋該名稱的from,然後再將它.show();再去運行同樣EXE檔時,應該是新的程序不再運行,而是將原來的EXE執行檔顯示在最前面,此時卻無法出現此效果,請問大大能給一些意見或想法嗎?
# re: [C#]EXE執行檔單獨運行小技巧, Posted by Jasper on 2010/7/9 下午 12:36 回覆
請問一下 此方法如果改了檔名 是不是就沒用了 即使同一隻程式?改了檔名 ProcessName就改了, 將好像不能避免掉改檔名~