1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

cscの作法 その460

Last updated at Posted at 2024-03-01

概要

cscの作法、調べてみた。
練習問題、やってみた。

練習問題

タスクトレイアイコンで、猫を走らせろ。

方針

64X16のビットマップを用意して、タイマーで切り出す。

参考にしたページ

写真

image.png

サンプルコード

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();
	}
}





以上

1
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?