Metro Styleアプリケーションでスタート画面のタイルに通知メッセージを表示する - C#

Windows 8のスタート画面のタイルにメッセージを表示するコードを紹介します。

UI

下図のUIを準備します。ボタンを一つ配置します。

コード

以下のコードを記述します。ボタンのClickイベントハンドラを実装します。

BlankPage.xaml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

// The Blank Page item template is documented
// at http://go.microsoft.com/fwlink/?LinkId=234238

namespace TileNotification
{
  /// <summary>
  /// An empty page that can be used on its own or navigated to within a Frame.
  /// </summary>
  public sealed partial class BlankPage : Page
  {
    public BlankPage()
    {
      this.InitializeComponent();
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.  The Parameter
    /// property is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
      XmlDocument content = new XmlDocument();
      string doc = "<title><visual version=\"1\" lang=\"en-US\">"
        + "<binding template=\"TileSquareBlock\">"
        + "<text id=\"1\">Hi!</text>"
        + "<text id=\"2\">こんにちわ</text>"
        + "</binding>"
        + "</visual></title>";
      
      content.LoadXml(doc);
      Windows.UI.Notifications.TileNotification tileNotification
        = new Windows.UI.Notifications.TileNotification(content);

      TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
      tileUpdater.Update(tileNotification);
    }
  }
}

解説

タイルにメッセージを表示するために以下の処理を実行します。
  1. XmlDocumentクラスのインスタンスを作成します。
  2. タイルにメッセージを表示するためのXMLを準備します
  3. XmlDocumentインスタンスのLoadXmlメソッドを用いXMLをXmlDocumentクラスに読み込みます。
  4. tileNotificationクラスのインスタンスを作成します。コンストラクタの引数にXmlDocumentクラスを与えます。
  5. TileUpdateManager.CreateTileUpdaterForApplicationメソッドを呼び出し、TileUpdaterクラスを取得します。
  6. 取得したTileUpdaterクラスのUpdateメソッドを呼び出しタイルの更新をします。

タイルにメッセージを表示するためのXMLは表示するレイアウトによりXMLが決まっています。どのようなXMLフォーマットがあるかを調べる方法はこちらの記事にて紹介しているプログラムで、タイルのXMLテンプレートを取得できます。

実行結果

アプリケーションを実行しフォームのボタンを押します。スタート画面に戻るとタイルにメッセージが表示されています。(下図右下のタイルです。)


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-03-15
iPentec all rights reserverd.