C#のフォームにBase64デコードしたアイコンを設定する |
7.2 アイコン (タイトルバー)
C# タイトルバーのアイコンの設定
Visual Studioを使用せず、アイコンリソースを作成することができないか調べたのでメモ。
まず、アイコンファイルをBase64の文字列に変換します。
変換プログラムはこちらを参考にしました。
Convert Image to Base64 String and Base64 String to Image
また、アイコンはこちらからお借りしました。
https://www.iconfinder.com/icons/51893/command_line_terminal_icon#size=128
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public class MakeBase64 {
public static void Main() {
byte[] imgData;
using(var fs = new FileStream("sample.ico", FileMode.Open)) {
imgData = new byte[fs.Length];
fs.Read(imgData, 0, imgData.Length);
}
string base64 = Convert.ToBase64String(imgData);
using(var sw = new StreamWriter("sample.ico.base64.txt")) {
//32文字ぐらいに区切って出力
while(0 < base64.Length) {
string line = "";
if (32 < base64.Length) {
line = "\"" + base64.Substring(0, 32) + "\" +";
base64 = base64.Substring(32);
} else {
line = "\"" + base64 + "\";";
base64 = "";
}
sw.WriteLine(line);
}
}
}
}
出力された文字列をプログラムで使用します。
Formアプリケーションはこのようになりました。
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : Form {
public static void Main() {
Form1 NewForm = new Form1();
Application.Run(NewForm);
}
public Form1() {
this.Size = new Size(200, 200);
this.Icon = CreateIcon();
}
private Icon CreateIcon() {
byte[] iconBytes = Convert.FromBase64String(IconBase64());
Icon icon = null;
using(var ms = new MemoryStream(iconBytes, 0, iconBytes.Length)) {
icon = new Icon(ms);
}
return icon;
}
private string IconBase64() {
return "AAABAAEAgIAAAAEAIAAoCAEAFgAAACgA" +
"AACAAAAAAAEAAAEAIAAAAAAAAAABABIL" +
"AAASCwAAAAAAAAAAAAD///8A////AP//" +
"/wD///8A////AP///wD///8A////AP//" +
(略)
}
}
狙い通りの動きです。
exe自体のアイコンを変更したい場合は、csc.exeにオプションをつけてコンパイルすればOK。
/win32icon:sample.ico
ひょとして、Formのアイコンも変わってくれるかな?と思いましたがダメでした。