概要
cscの作法、調べてみた。
練習問題、やってみた。
練習問題
タスクトレイアイコンで、猫を走らせろ。
方針
64X16のビットマップを用意して、タイマーで切り出す。
参考にしたページ
写真
サンプルコード
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
static class MyIconUtil {
static class NativeMethods {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static bool DestroyIcon(IntPtr handle);
}
public static Icon CreateIcon(byte[,] iconDot) {
Bitmap bmp = new Bitmap(iconDot.GetLength(0), iconDot.GetLength(1));
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
}
for (int y = 0; y < iconDot.GetLength(1); y++)
{
for (int x = 0; x < iconDot.GetLength(0); x++)
{
if (iconDot[x, y] != 0)
{
bmp.SetPixel(x, y, Color.Black);
}
}
}
IntPtr Hicon = bmp.GetHicon();
return Icon.FromHandle(Hicon);
}
public static void DestroyIcon(Icon icon) {
NativeMethods.DestroyIcon(icon.Handle);
}
}
class TaskTrayTest {
static readonly int W = 16;
static readonly int H = 16;
NotifyIcon trayIcon;
byte[,] iconDot;
System.Windows.Forms.Timer timer;
int n = 0;
Bitmap cat;
TaskTrayTest() {
trayIcon = new NotifyIcon();
iconDot = new byte[W, H];
cat = new Bitmap("cat.bmp");
Icon tmpIcon = MyIconUtil.CreateIcon(iconDot);
trayIcon.Icon = tmpIcon;
trayIcon.Visible = true;
trayIcon.Text = "cat";
var menu = new ContextMenuStrip();
var menuItem = new ToolStripMenuItem();
menu.Items.AddRange(new ToolStripMenuItem[] {
new ToolStripMenuItem("E&xit", null, (s, e) => {
timer.Stop();
Application.Exit();
}, "Exit")
});
trayIcon.Click += (s, e) => {
};
trayIcon.ContextMenuStrip = menu;
timer = new System.Windows.Forms.Timer();
timer.Interval = 200;
timer.Tick += (sender, e) => {
UpdateBoard();
};
timer.Start();
}
void UpdateBoard() {
n++;
if (n > 3)
n = 0;
int i = n * 16;
Rectangle rect = new Rectangle(i, 0, 16, 16);
Bitmap bmpNew = cat.Clone(rect, cat.PixelFormat);
IntPtr Hicon = bmpNew.GetHicon();
Icon oldIcon = trayIcon.Icon;
trayIcon.Icon = Icon.FromHandle(Hicon);
MyIconUtil.DestroyIcon(oldIcon);
}
[STAThread]
static void Main(string[] args) {
new TaskTrayTest();
Application.Run();
}
}
以上