C#實現只許一個實例運行

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace TST.SINGLE
{
    publicclass TSTPGM
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        staticvoid Main()
        {
            bool createdNew =true;
            using (Mutex mutex =new Mutex(true, "MyApplicationName", out createdNew))
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                }
                else
                {
                    Process current = Process.GetCurrentProcess();
                    foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            IntPtr hWnd = process.MainWindowHandle;
                            ShowWindowAsync(hWnd, WS_SHOWNORMAL); //調用api函數,正常顯示窗口
                            SetForegroundWindow(hWnd);//將窗口放置最前端。                            break;
                        }
                    }
                }
            }
        }

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int WS_SHOWNORMAL = 1;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章