하나의 프로세스만 실행할 수 있는 실례

2879 단어 인스턴스
using System;

using System.Runtime.InteropServices;

using System.Windows.Forms;

using System.Diagnostics;

using System.Reflection;

public class OneInstnace

{

[STAThread]

public static void Main()

{

//         

        Process instance = RunningInstance();

if (instance == null)

{

//        ,       

            Application.Run(new Form());

}

else

{

//       

            HandleRunningInstance(instance);

}

}

public static Process RunningInstance()

{

Process current = Process.GetCurrentProcess();

Process[] processes = Process.GetProcessesByName(current.ProcessName);

//              

        foreach (Process process in processes)

{

//       

            if (process.Id != current.Id)

{

//     EXE    

                if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==

current.MainModule.FileName)

{

//         

                    return process;

}

}

}

//       ,  Null

        return null;

}

public static void HandleRunningInstance(Process instance)

{

//              

        ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);

//       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);

private const int WS_SHOWNORMAL = 1;

}

좋은 웹페이지 즐겨찾기