IT/C#

C# - [Winform] 중복실행 방지

!? 2022. 2. 7.

목차

    C# - [Winform] 중복실행 방지

     

    어플리케이션 실행 시 중복 방지를 위해 Program.cs 파일을 수정.

    1. using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, @"formTest.exe", out createdNew))

    - 해당 어플리케이션이 실행되어 있는지 체크

     

     

     

     

    2. SetForegroundWindow(process.MainWindowHandle);

    - 해당 어플리케이션이 실행 중이라면, 최상위로 활성화

     

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace formTest
    {
        static class Program
        {
            /// <summary>
            /// 해당 애플리케이션의 주 진입점입니다.
            /// </summary>
            [STAThread]
            static void Main()
            {
                bool createdNew = false;
                using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, @"formTest.exe", out createdNew))
                {
                    if (createdNew)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
    
                        Application.Run(new Form1());
                    }
                    else
                    {
                        Process current = Process.GetCurrentProcess();
                        foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                        {
                            if (process.Id != current.Id)
                            {
                                SetForegroundWindow(process.MainWindowHandle);
                                break;
                            }
                        }
                    }
                }
            }
    
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            static extern bool SetForegroundWindow(IntPtr hWnd);
        }
    }

     

     

    댓글