检查PictureBox 中的位置是否为Transparent 取决于PictureBox 的Image 和SizeMode 属性。
您不能简单地使用Bitmap 的GetPixel,因为图像位置和大小根据SizeMode 不同。你应该先根据SizeMode检测Image的大小和位置:
public bool HitTest(PictureBox control, int x, int y)
{
var result = false;
if (control.Image == null)
return result;
var method = typeof(PictureBox).GetMethod("ImageRectangleFromSizeMode",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var r = (Rectangle)method.Invoke(control, new object[] { control.SizeMode });
using (var bm = new Bitmap(r.Width, r.Height))
{
using (var g = Graphics.FromImage(bm))
g.DrawImage(control.Image, 0, 0, r.Width, r.Height);
if (r.Contains(x, y) && bm.GetPixel(x - r.X, y - r.Y).A != 0)
result = true;
}
return result;
}
然后你可以简单地使用HitTest方法来检查鼠标是否在PictureBox的不透明区域上:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (HitTest(pictureBox1,e.X, e.Y))
pictureBox1.Cursor = Cursors.Hand;
else
pictureBox1.Cursor = Cursors.Default;
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (HitTest(pictureBox1, e.X, e.Y))
MessageBox.Show("Clicked on Image");
}
还将BackColor 设置为Color.Transparent 只会使PictureBox 相对于其父级透明。例如,如果您在 Form 中有 2 个 PictureBox 设置透明背景色,只是因为您看到了表单的背景。要制作支持透明背景的PictureBox,您应该自己绘制控件后面的内容。你可以在这篇文章中找到TransparentPictureBox:How to make two transparent layer with c#?