개발언어/.NET

WPF Application StartUp Event 핸들러를 이용한 처리

공장장코난 2019. 11. 30. 15:16

VisualStudio로 WPF 프로젝트 생성시 기본 MainWindow로 호출 된다.
프로그램 배포를 위해 Starter Application을 만들면서 MainWindow 생성 이전에 다른 작업 수행 후
MainWindow를 호출할 생각인데, 이때 StartUp event 핸들러를 이용해서 작업을 진행 한다.

WPF의 Application 시작점은 App.xaml 이다. App.xml을 열어보면 아래 코드를 확인할 수 있는데
StartupUri을 통해 MainWindow.xaml 콜하는 있는걸 확인할 수 있다. 
<Application x:Class="Test.Starter.App"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:local="clr-namespace:CVS.AlbaBot.Updater"
                  StartupUri="MainWindow.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>       
         
원하는 작업을 위해 StartupUri 대는 StartUp event 핸들러를 등록하고 App.cs에 StartUp 델리게이트 이벤트를 등록 한다.
<Application x:Class="Test.Starter.App"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                  xmlns:local="clr-namespace:CVS.AlbaBot.Updater"
                  Startup="OnStartup">
    <Application.Resources>

    </Application.Resources>
</Application> 

App.cs
...
public partial class App : Application
{
    private void OnStartup(object sender, StartupEventArgs e)
    {
        //Do something...

        new MainWindow.ShowDialog();

        Environment.Exit(0);
    }
}

MainWindow 호출전에 설정값을 불러오는 등의 원하는 작업을 수행하고 MainWindow를 호출 한다.


작업 끝...