LoginSignup
1
2

More than 5 years have passed since last update.

Visual Studio / WPF > イベント > アプリ実行時に何かをする | link:Application_Startup と Window_Loaded または Window_Initialized の同時使用での注意

Last updated at Posted at 2017-04-29
動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

アプリ起動時に何かを処理する、という処理を検討してみた。

参考: https://msdn.microsoft.com/ja-jp/library/system.windows.application.startup(v=vs.110).aspx

App_Startup()というのを使うようだ。

手順

  • App.xamlの編集
    • <Application x:Class=...のタグ(?)にてStartup=を追加
    • <新しいイベントハンドラー>を選択
      • Application_Startupが追加された
      • App_Startupではない?
    • F12でC# script編集画面に移動
    • 処理を実装

コード

App.xaml
<Application x:Class="_170430_t0723_WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:_170430_t0723_WpfApp1"
             StartupUri="MainWindow.xaml"
             Startup="Application_Startup">
    <Application.Resources>

    </Application.Resources>
</Application>
App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace _170430_t0723_WpfApp1
{
    /// <summary>
    /// App.xaml の相互作用ロジック
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            MessageBox.Show("Good morning");
        }
    }
}

はまりポイント

一度追加したApplication_Startup()の消し方が不明。

下手に消すと、コードの整合性がとれなくなるのか、IDEエラーが発生して修正できなくなる。

C++ Builderの方がこの点では良い。

リンク

Application_Startup と Window_Loaded または Window_Initialized の同時使用での注意 @ パイナップルの芯

両方書いておくと先に App.xaml.cs で ShutDown() が呼ばれてもアプリは終了せず、そのまま MainWindow の処理が進んでいきます……。

上記のApplication_Startup()以外にもWindow_Loaded()というのがあるようだ。
また、実装仕方によっては「はまる」ポイントがありそう。

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2