public partial class Form1 : Form
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);
public struct IconInfo
{
public bool fIcon; // アイコンの場合 true, カーソルの場合 false
public int xHotspot; // カーソルのホットスポットの X 座標
public int yHotspot; // カーソルのホットスポットの Y 座標
public IntPtr hbmMask; // 透過用のビットマップハンドル
public IntPtr hbmColor; // 画像用のビットマップハンドル
}
public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
IntPtr ptr = bmp.GetHicon();
IconInfo tmp = new IconInfo();
GetIconInfo(ptr, ref tmp);
tmp.xHotspot = xHotSpot;
tmp.yHotspot = yHotSpot;
tmp.fIcon = false;
ptr = CreateIconIndirect(ref tmp);
return new Cursor(ptr);
}
// ビットマップファイルからカーソルファイルをつくる
void MakeCursorFromBmpFile(string bitmapFilePath, string cursorFilePath, int xHotSpot, int yHotSpot)
{
Image img = Image.FromFile(bitmapFilePath);
Bitmap bitmap = new Bitmap(32, 32, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bitmap);
g.DrawImage(img, new Rectangle(0, 0, 32, 32));
g.Dispose();
Cursor cursor = CreateCursor(bitmap, xHotSpot, yHotSpot);
Icon icon = Icon.FromHandle(cursor.Handle);
Stream outStream = new FileStream(cursorFilePath, FileMode.Create, FileAccess.Write);
icon.Save(outStream);
//後始末
outStream.Close();
bitmap.Dispose();
icon.Dispose();
img.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "カーソルファイル|*.cur";
if(dialog.ShowDialog() != DialogResult.OK)
return;
if(!File.Exists(textBoxForFilePath1.Text))
{
MessageBox.Show("Bitmapファイルのバスが不正です。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int x = int.Parse(textBoxHotSpotX.Text);
int y = int.Parse(textBoxHotSpotY.Text);
MakeCursorFromBmpFile(textBoxForFilePath1.Text, dialog.FileName, x, y);
}
catch
{
}
}
}