본문 바로가기

Programing (프로그래밍)/WPF & C# (C Sharp)

WPF & C# - 중복실행방지 2가지 방법 ( 이중실행 / Titile명 기준 / 뮤택스 / 뮤텍스 / Mutex )

728x90
반응형


 WPF & C# - 중복실행방지 2가지 방법 ( 이중실행 / Titile명 기준 / 뮤택스 / 뮤텍스 / Mutex )



MainWindow.xaml.cs - 타이틀명 기준



1
2
3
4
5
6
7
8
9
10
11
12
// 이중실행 방지를 위한 DLL import
[DllImportAttribute("user32.dll", EntryPoint = "FindWindow")]
public static extern int FindWindow(string clsName, string wndName);
 
public MainWindow()
{
    InitializeComponent();
 
    // 이중실행 방지를 위한 코드 ( TITLE 명을 기준으로 한다.) 
    this.Title = "Title명";
    if (FindWindow(null, Title) > 1) Close();
}
cs


[윈도우 ]

 - 기존 실행되던 Window 창의 제목 타이틀 (Title)을 찾아서 숫자파악 후 시작시 0이 아닐 시 종료 됨




MainWindow.xaml.cs - Mutex 이용



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public MainWindow()
{
    this.Title = "Title명";
    Duplicate_execution(Title);   // 중복실행 방지
    initSetting();   // 초기설정
}
 
// 중복실행방지 - Mutex 활용
Mutex mutex = null;
private void Duplicate_execution(string mutexName)
{
    try
    {
        mutex = new Mutex(false, mutexName);
    }
    catch (Exception ex)
    {
        //                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace + "\n\n" + "Application Exiting…", "Exception thrown");
        Application.Current.Shutdown();
    }
    if (mutex.WaitOne(0false))
    {
        InitializeComponent();
    }
    else
    {
        //                MessageBox.Show("Application already startet.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
        Application.Current.Shutdown();
    }
}
cs


* 중복실행체크하여 Initialize 실행여부를 결정한다.


728x90
반응형