White Whale Studio

C# 중복 실행시 기존프로그램을 활성화 하기 본문

IT Engineering/C#.net

C# 중복 실행시 기존프로그램을 활성화 하기

glorymind 2023. 2. 13. 15:04
반응형

현재 제가 필요했던 시나리오는 다음과 같습니다.

1. 프로그램을 실행

2. 프로그램이 실행이 되어있는줄 모르고 재실행을 할 경우, 중복실행 알림 메시지를 띄우지 않고 기존 프로그램을 재활성화 하기

일반적으로는 기존 프로그램을 살려두고 다음으로 실행하는 프로그램에서 중복 실행되었음을 판단하여 화면에 표시하도록 하는  프로세스를 사용하였는데 위와 같은 프로세스도 괜찮은 듯하여 작업해보았습니다.

소스는 다음과 같습니다.

주석을 보시면서 참고하시면 편할것 같네요.

 
[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);
 
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
 
const int WM_SHOWWINDOW = 0x0018;
public const int HT_CAPTION = 0x2;
 
static void Main()
        {
            try
            {
                //System.Diagnostics.Process[] processes = null;
                //string strCurrentProcess = System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToUpper();
                //processes = System.Diagnostics.Process.GetProcessesByName(strCurrentProcess);
                //if (processes.Length > 1)
                //{
                //    MessageBox.Show(string.Format("'{0}'\r\n is already Running.", "Application Name"), "Running Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}
                //// Windows Form Title Text
                string windowTitle = "Winform Title Text";
                //// Get Process ID
                IntPtr prtWnd = (IntPtr) FindWindow(null, windowTitle);
 
                //// 해당 프로세스가 존재하는 경우 명령어 
                if (prtWnd != IntPtr.Zero)
                {
                    SendMessage(prtWnd, WM_SHOWWINDOW, HT_CAPTION, 0);
                    return;
                }
                else //// 중복되는 프로그램이 없는 경우 일반적인 실행
               {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frmMain());
                }
            }
            catch (Exception ex)
            {
                LogHelper.FileLog().WriteErrorLog(string.Format("Method : {0}\n Error Message : {1}"System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message + "/" + ex.StackTrace));
            }
        }        
cs

주의 할 점은 string windowTitle = "";

위 변수에 들어가야될 데이터는 Winform의 Title Text입니다, 프로젝트 명이 아닙니다.

Windows 명령어 사용을 위해 위 소스와 같이 DLLImport 해주시고 사용하시면 됩니다.

저 명령어를 받는 쪽은 Windows Form 중에서도 메인 폼입니다.

메인 폼에서 받는 부분을 기술하면 다음과 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const int WM_SHOWWINDOW = 0x0018;
 
protected override void WndProc(ref Message m)
        {            
            base.WndProc(ref m);
            switch (m.Msg)
            {                
                case WM_SHOWWINDOW:
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    break;
            }
        }
cs

위 내용을 보면 저의 경우에는 화면을 표시하고 WindowsState를 Normal로 설정하여 화면이 다시 표시되도록 처리했습니다.

위와 같이 설정하게 되면

중복 실행시 먼저 실행된 프로그램이 비활성화(숨겨져 있거나 최소화 되어있는 경우)된 경우

화면에 표시가 됩니다.

 

이상입니다.

 

반응형
Comments