標籤:
有這麼個需求,軟體只能運行一個執行個體,軟體運行後可以讓其隱藏運行
再次運行這個軟體的時候就讓正在啟動並執行執行個體顯示出來
=================================
當軟體隱藏後沒辦法拿到控制代碼
於是只有第一次啟動並執行時候講控制代碼儲存下來,於是有了下面的
1 private void HideForm() 2 { 3 string handlestr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToInt32().ToString(); 4 string path = Application.StartupPath + "\\Handle"; 5 if (!File.Exists(path)) 6 { 7 File.Create(path).Close(); 8 } 9 using (StreamWriter writer = new StreamWriter(path, false))10 {11 writer.Write(handlestr);12 }13 this.Hide();14 }View Code
哪裡需要隱藏就調用
下面是控制
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Windows.Forms; 5 using System.Diagnostics; 6 using System.Runtime.InteropServices; 7 using System.IO; 8 9 namespace NIKE.Client10 {11 static class Program12 {13 /// <summary>14 /// 應用程式的主進入點。15 /// </summary>16 [STAThread]17 static void Main()18 {19 //StaticPass.cf = new ClientForm();20 //Application.EnableVisualStyles();21 //Application.SetCompatibleTextRenderingDefault(false);22 //Application.Run(new FormMain());23 bool ret;24 System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);25 if (ret)26 {27 System.Windows.Forms.Application.EnableVisualStyles(); //這兩行實現 XP 可視風格 28 //System.Windows.Forms.Application.DoEvents(); //這兩行實現 XP 可視風格 29 Application.SetCompatibleTextRenderingDefault(false);30 System.Windows.Forms.Application.Run(new FormMain());31 // Main 為你程式的主表單,如果是控制台程式不用這句 32 mutex.ReleaseMutex();33 }34 else35 {36 37 string path = Application.StartupPath + "\\Handle";38 int handle = 0;39 using (StreamReader reader = new StreamReader(path))40 {41 handle = int.Parse(reader.ReadToEnd());42 }43 IntPtr i = new IntPtr(handle);44 bool isok = ShowWindow(i, 1);45 SetForegroundWindow(i);46 // SetForegroundWindow(hWnd);47 // MessageBox.Show(null, "有一個和本程式相同的應用程式已經在運行,請不要同時運行多個本程式。\n\n本次開啟無效", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);48 // 提示資訊,可以刪除。 49 Application.Exit();//退出程式 50 }51 }52 53 [DllImport("user32.dll")]54 private static extern bool SetForegroundWindow(IntPtr hWnd);55 [DllImport("user32.dll")]56 private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 57 private const int SW_SHOWNORMAL = 1;58 59 }60 }View Code
c# 控制職能運行單一執行個體,再次運行顯示已經啟動並執行執行個體