본문 바로가기
프로그래밍&IT/C# (Winfrom, WPF)

[WPF] The Application

by 성장의 용 2025. 8. 4.
728x90
반응형

The Application (애플리케이션)

1. Application 클래스란?

 

  • WPF에서 애플리케이션을 정의하고 관리하는 클래스.
  • System.Windows.Application을 기반으로 하며, 전역적인 애플리케이션 상태, 리소스, 이벤트 등을 관리함.
  • 보통 App.xaml/App.xaml.cs에 정의됨.

 

2. App.xaml / App.xaml.cs

  • App.xaml: 리소스 정의, 시작 설정 (StartupUri 등)
  • App.xaml.cs: Application 클래스의 코드 비하인드. 이벤트 핸들링(예: Startup, Exit 등)이 여기에 있음.
// xaml
<Application x:Class="MyApp.App"
             StartupUri="MainWindow.xaml"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>

// cs
public partial class App : Application
{
    private void App_Startup(object sender, StartupEventArgs e)
    {
        // 커스텀 로직 삽입 가능
    }
}

3. 애플리케이션 수명 주기 (Lifecycle) 이벤트

  • Startup: 앱 시작 시 발생
  • Exit: 앱 종료 시 발생
  • DispatcherUnhandledException: 예외 처리
  • SessionEnding: 세션 종료 시
this.Startup += new StartupEventHandler(App_Startup);
this.Exit += new ExitEventHandler(App_Exit);

4. Application.Current

  • 현재 실행 중인 Application 인스턴스에 접근할 수 있음.
  • 예: 현재 리소스, Windows 목록, 설정 등 접근 가능.
Application.Current.MainWindow.Title = "Hello";

5. 윈도우 관리

  • WPF 앱은 여러 Window를 동시에 띄울 수 있음.
  • Application.Current.Windows 컬렉션을 통해 모든 열린 창에 접근 가능.
foreach (Window window in Application.Current.Windows)
{
    // 윈도우 제목 출력
    Console.WriteLine(window.Title);
}

6. Shutdown 모드

애플리케이션이 언제 종료되는지를 제어하는 속성

  • OnLastWindowClose (기본값)
  • OnMainWindowClose
  • OnExplicitShutdown
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;

7. 명령줄 인자 (Command-Line Arguments)

StartupEventArgs의 Args 속성으로 전달받음

private void App_Startup(object sender, StartupEventArgs e)
{
    foreach (string arg in e.Args)
    {
        Console.WriteLine(arg);
    }
}

8. 리소스(Resource) 관리

App.xaml에서 전역 리소스를 정의하여 모든 Window/UserControl에서 사용 가능

<Application.Resources>
    <SolidColorBrush x:Key="MainColor" Color="CornflowerBlue"/>
</Application.Resources>

 

 

Application 주요 이벤트

이벤트 이름 발생 시점 주요 목적 대표 시나리오
Startup 앱이 시작될 때 초기 설정, 명령줄 인자 처리, 초기 창 수동 실행 로그 기록, 조건부 초기화, 다중 창 설정
Exit 앱이 종료될 때 종료 전 정리 작업 로그아웃, 파일 저장, 리소스 해제
DispatcherUnhandledException UI 스레드에서 처리되지 않은 예외 발생 시 전역 예외 처리 앱 비정상 종료 방지, 예외 로그 저장
SessionEnding 사용자 로그오프/종료 시도 시 앱이 강제로 종료되기 전 알림 문서 저장 경고, 사용자 확인
Activated 앱이 포커스를 얻었을 때 사용자 활동 재개 감지 화면 갱신, 알림 제거 등
Deactivated 앱이 포커스를 잃었을 때 사용자 이탈 감지 타이머 정지, UI 흐림 처리 등

 

Localization

  • 리소스(Resource)를 활용해서 UI 텍스트를 다국어로 바꿔주는 방식.
  • Application 레벨에서도 이 리소스를 잘 활용하면 전역적으로 언어를 전환할 수 있다.

1. 리소스(.resx) 파일을 사용한 다국어 처리

* 각 언어별로 .resx 파일을 만들어서 문자열을 정의할 수 있다.

  • Resources.resx (기본)
  • Resources.ko.resx (한국어)
  • Resources.en.resx (영어)

* Visual Studio에서 Properties 폴더에 생성하거나, 별도의 Resource 폴더에 추가 가능

2. 코드에서 리소스 접근

 

  • 현재 실행 중인 UI culture에 따라 자동으로 해당 언어 리소스를 로드한다.
  • 언어 전환 시에는 Thread.CurrentThread.CurrentUICulture을 변경하면 된다.

 

string greeting = Properties.Resources.Greeting;

3. 언어 변경 코드 (동적 언어 전환)

변경 후, 창을 새로 로드하거나 수동으로 텍스트를 다시 바인딩해야 UI 반영이 된다.

using System.Globalization;
using System.Threading;

Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");

4. XAML에서 바인딩 (StaticResource 또는 MarkupExtension 활용)

기본적으로는 XAML에서 직접 .resx를 바인딩하는 건 복잡하므로,

보통 Binding + IValueConverter 또는 MarkupExtension을 활용한다.

// cs
public class LocTextExtension : MarkupExtension
{
    public string Key { get; set; }
    public LocTextExtension(string key) => Key = key;

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Properties.Resources.ResourceManager.GetString(Key, Thread.CurrentThread.CurrentUICulture);
    }
}

//xaml
<TextBlock Text="{local:LocText Greeting}" />

5. Application 수준에서 다국어 리소스를 관리

App.xaml.cs에서 언어를 설정하고 전체 리소스를 다시 로딩할 수 있다.

public static void ChangeLanguage(string cultureName)
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
    
    // 창 새로고침 또는 리소스 재적용 필요
}

6. 주의 사항

 

  • 리소스 자동 전환은 "초기 실행"에만 작동하므로 실시간 전환은 수동 처리 필요
  • 사용자 언어 선택 저장 시에는 Properties.Settings.Default 등을 활용
  • ResxFileCodeGenerator가 설정되어 있어야 Properties.Resources에 접근 가능

 

'프로그래밍&IT > C# (Winfrom, WPF)' 카테고리의 다른 글

[WPF] Commands  (0) 2025.08.06
[WPF] Element Binding  (4) 2025.08.04
[WPF] Controls  (3) 2025.08.04
[WPF] Routed Events  (1) 2025.08.03
[WPF] WPF의 기본 레이아웃 (Layout)  (4) 2025.08.03