Winform 프로그램 멀티캐스트 금지 & & 멀티캐스트 금지 및 첫 번째 창 두 번째 활성화

9991 단어
1. 멀티태스킹 금지, Mutex 자물쇠 활용
Program에서cs에서 Mutex 잠금 사용
bool createNew;
using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew)) { if (createNew) { Application.Run(new Form1()); } else { MessageBox.Show(" ...") System.Threading.Thread.Sleep(1000); System.Environment.Exit(1); } }

혹은
static void Main()
{
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     //Application.Run(new MainForm());

      bool CreateNewForm;//                     
      System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out CreateNewForm);//       
      if (CreateNewForm)//
      {
           Application.Run(new MainForm());
           instance.ReleaseMutex();
      }
      else
      {
           Application.Exit();
      }
}

2. 여러 번 여는 것을 금지하고 두 번째 클릭하면 첫 번째 창의 핸들을 활성화합니다using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Diagnostics; using System.Reflection; namespace NetCardUI { static class Program { /// /// /// /// /// 。 , ShowWlndow /// , ; , [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); /// /// , 。 , 。 ////// /// /// , ; , [DllImport("User32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); private const int SW_SHOWNOMAL = 1; private static void HandleRunningInstance(Process instance) { ShowWindowAsync(instance.MainWindowHandle, SW_SHOWNOMAL);// SetForegroundWindow(instance.MainWindowHandle);// } private static Process RuningInstance() { Process currentProcess = Process.GetCurrentProcess(); Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName); foreach (Process process in Processes) { if (process.Id != currentProcess.Id) { if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == currentProcess.MainModule.FileName) { return process; } } } return null; } /// ////// [STAThread] static void Main() { Process process = RuningInstance(); if (process == null) { Application.Run(new MainForm()); } else { HandleRunningInstance(process); //System.Threading.Thread.Sleep(1000); //System.Environment.Exit(1); } } } }
 
전재 대상:https://www.cnblogs.com/javier520/p/10672729.html

좋은 웹페이지 즐겨찾기