恥ずかしいのですが、Cradle Clockのソースコードです。
- はじめは単純に時計を書いて、
- 次に数値画像から画像を取り出す処理にして、
- 最後にバッテリー状態変更に伴う処理(OSへの登録処理)
という感じで作っていきました。
----
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.WindowsMobile;
using Microsoft.WindowsMobile.Status;
namespace CradleClock
{
public partial class Form1 : Form
{
ここがからくり。電源の状態が変わったことを示す、PowerBatteryStatuをアプリケーションの起動トリガとして利用します。w,h,bmp は表示する時計の文字の情報を格納します。
static SystemState state
= new SystemState(SystemProperty.PowerBatteryState);
int w, h;
Bitmap bmp;
初期化処理。Form1_loadでは、画面の解像度に合わせて適した数値画像ファイルを読み込みます。
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (this.Width > 320)
bmp = new Bitmap(
System.IO.Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase)
+ @"\digital.jpg");
else
bmp = new Bitmap(
System.IO.Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase)
+ @"\digitals.jpg");
w = bmp.Width / 11;
h = bmp.Height;
}
描画処理。時間を文字列に変更して、1文字ごとに対応する画像データを表示します。n桁目にmの数字を表示する処理は drawnum 関数にまとめて有ります。
private void Form1_Paint(object sender, PaintEventArgs e)
{
DateTime time = DateTime.Now;
Graphics g = e.Graphics;
drawnum(g, 0, time.Hour / 10);
drawnum(g, 1, time.Hour % 10);
if(time.Second%2==0)
drawnum(g, 2, 10);
drawnum(g, 3, time.Minute / 10);
drawnum(g, 4, time.Minute %10);
g.Dispose();
}
private void drawnum(Graphics g, int pos, int num)
{
if ((pos == 0)&& (num == 0)) return;
int ph = (this.Height - h) / 2;
g.DrawImage(
bmp,
new Rectangle((this.Width - w * 5) / 2 + pos * w, ph, w, h),
new Rectangle(num*w, 0, w, h),
GraphicsUnit.Pixel);
}
timerコントロールは1秒=1000msec に設定しておいて、1秒ごとに仮面の書き換え(Invalidate)をします。描画処理は OnPaint
private void timer1_Tick(object sender, EventArgs e)
{
this.Invalidate();
}
終了処理。2つの終了処理が有ります。this.close はこのフォームが閉じて、その結果アプリケーションが終了。Application.exit()はアプリケーションをいきなり親元から終了します。this.Closeではフォームを閉じる前に Form1_Closeed イベントが発生します。
Form1_loadでは、画面の解像度に合わせて適した数値画像ファイルを読み込みます。
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
アプリケーションの登録処理。終了時に次回のアプリケーション自動起動の登録をします。起動条件は バッテリーステータスが、Charging(充電中)になった(Equal)時。あとは、起動するアプリケーション(自分自身)のファイルパスをつけて登録します。
private void Form1_Closed(object sender, EventArgs e)
{
state.ComparisonType = StatusComparisonType.Equal;
state.ComparisonValue = BatteryState.Charging;
state.EnableApplicationLauncher(
"DigitalClock",
Assembly.GetExecutingAssembly().GetName().CodeBase);
}
ボタン色変更処理。3つのボタンはフォーカスされたら白文字に、フォーカスが外れたらグレーの文字にします。
private void button_GotFocus(object sender, EventArgs e)
{
(sender as Button).ForeColor = Color.White;
}
private void button_LostFocus(object sender, EventArgs e)
{
(sender as Button).ForeColor = Color.Gray;
}
}
}
トラックバック:
http://blogs.shintak.info/archive/2008/09/02/45866.aspx