C#程式多使用者只啟動一個進程的方法[轉載]

來源:互聯網
上載者:User

著作權聲明:轉載時請以超連結形式標明文章原始出處和作者資訊及本聲明
http://greenlandy.blogbus.com/logs/14388828.html

Code Snippet
  1. [STAThread]
  2.      private static void Main()
  3.      {
  4.          Application.EnableVisualStyles();
  5.          Application.SetCompatibleTextRenderingDefault(false);
  6.          var wb = new Form1();
  7.          Process current = Process.GetCurrentProcess();
  8.          bool newinstance = true;
  9.          Process[] processes = Process.GetProcessesByName(current.ProcessName);
  10.  
  11.          //?曆正在有相同名字??的常式  
  12.          foreach (Process process in processes)
  13.          {
  14.              //忽略現有的常式  
  15.              if (process.Id != current.Id)
  16.              {
  17.                  //確保常式從EXE檔案??  
  18.                  if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  19.                  {
  20.                      //?回另一個常式執行個體  
  21.                      current = process;
  22.                      newinstance = false;
  23.                      break;
  24.                  }
  25.              }
  26.          }
  27.          if (newinstance)
  28.          {
  29.              Application.Run(wb);
  30.          }
  31.          else
  32.          {
  33.              ShowWindowAsync(current.MainWindowHandle, 1);
  34.  
  35.              //?置真執行個體程為foreground   window  
  36.              SetForegroundWindow(current.MainWindowHandle);
  37.          }
  38.      }

引入這兩個API函數

Code Snippet
  1. [DllImport("User32.dll")]
  2. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  3.  
  4. [DllImport("User32.dll")]
  5. private static extern bool SetForegroundWindow(IntPtr hWnd);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.