상세 컨텐츠

본문 제목

[단일 프로세스 실행]

C#

by 탑~! 2010. 12. 31. 15:02

본문


Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    static class Program
    {
        public static EventWaitHandle s_ewh;
        public static Form s_mainForm = null;
        static bool s_bRun = true;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                s_ewh = EventWaitHandle.OpenExisting("OneInstance.ThisProgram");
                if (s_ewh != null)
                {
                    s_ewh.Set();
                    return;
                }
            }
            catch
            {
            }

            if (s_ewh == null)
            {
                s_ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "OneInstance.ThisProgram");
            }

            Thread thread = new Thread(WaitInstanceEvent);
            thread.IsBackground = true;
            thread.Start();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            s_mainForm = new Form1();
            Application.Run(s_mainForm);

            s_mainForm = null;
            s_bRun = false;
            s_ewh.Set();
        }


        static void WaitInstanceEvent(object state)
        {
            while (s_bRun)
            {
                s_ewh.WaitOne();
                if (s_mainForm == null)
                {
                    continue;
                }

                Form1.s_ctxThread.Post(new SendOrPostCallback( (object thisState) =>
                    {
                        ((Form1)s_mainForm).ShowMyWindow();
                    }
                ), null);
            }
        }
    }
}

 

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public static SynchronizationContext s_ctxThread;

        public Form1()
        {
            InitializeComponent();
            s_ctxThread = WindowsFormsSynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        public void ShowMyWindow()
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
            }

            this.TopMost = true;
            this.TopMost = false;
        }
    }
}

관련글 더보기