본문 바로가기

C# Language

실행할 프로그램이 process에 있는지 확인하기

오늘은 C#으로 프로그램을 만든 후 실행을 시켰을 때,

이미 자신이 만든 프로그램이 실행되고 있는지 없는지를 알려고 할 때

사용하는 구문 입니다.


//Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics; // Process 사용하기 위해서.. 

namespace _20106_dataGridViewTest
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            // 이 프로그램이 실행 중인지 아닌지 확인하는 부분
            if (IsApplicationAlreadyRunning())
            {
                MessageBox.Show("이 프로그램은 실행 중입니다.");
                Application.Exit();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        
        // 이 프로그램이 실행 중이면 true 아니면 false
        static public bool IsApplicationAlreadyRunning()
        {
            string proc = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(proc);

            if (processes.Length > 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}



두번째 방법은 Mutex를 이용하는 방법입니다.

//Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading; // Mutex를 사용하기 위해

namespace _20106_dataGridViewTest
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            // 뮤텍스 Name 설정
            string mutexName = "Mutex_set_passwd_1234";
            Mutex mutex_ = new Mutex(true, mutexName);

            // 1초 동안 뮤텍스가 있는지 확인
            TimeSpan timespan = new TimeSpan(0, 0, 1);
            bool success = mutex_.WaitOne(timespan);

            // 이미 프로그램 실행중인지 확인
            if (!success)
            {
                MessageBox.Show("이 프로그램은 실행 중입니다.");
                Application.Exit();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

}



참조페이지 :
http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=17&MAEULNO=8&no=142463&ref=142458&page=1#Contents142463

http://www.csharpstudy.com/Tips/Tips-Singleprocess.aspx

※ 이 글의 첫번째 소스는 데브피아 정신균님의 답변을 수정한 글입니다.