你有两个选择:
只有选项一才可行如果你可以创建一个Region,它需要一个GraphicsPath,这意味着你需要创建你需要的形状 Graphics 原语,如线条和曲线等。
如果您只有具有透明度的Bitmap,最好不要将Button 与Region 一起使用。
相反,您可以使用 Button1 并在每次点击时检查点击像素的透明度。
如果它是透明的,则调用其下方控件的单击事件..
private void Button1_MouseClick(object sender, MouseEventArgs e)
{
Size r = Button1.BackgroundImage.Size;
// check that we have hit the image and hit a non-transparent pixel
if ((e.X < r.Width && e.Y < r.Height) &&
((Bitmap)Button1.BackgroundImage).GetPixel(e.X, e.Y).A != 0)
{
Console.WriteLine("BUTTON clicked"); // test
// do or call your click actions here!
}
// else pass the click on..
else
{
// create a valid MouseEventArgs
MouseEventArgs ee = new MouseEventArgs(e.Button, e.Clicks,
e.X + Button1.Left, e.Y + Button1.Top, e.Delta);
// pass it on to the stuff below us
pictureBox1_MouseClick(pictureBox1, ee);
Console.WriteLine("BUTTON NOT clicked"); // test
}
}
请注意,检查假定您具有正常布局,按钮图像位于左上角并且没有缩放。如果您需要缩放图像,您应该保留一个缩放位图来进行检查。但是如果您可以使用未缩放的图像,您应该这样做,因为这样看起来会更好。
请注意我如何为下面的控件创建正确的MouseEventArgs 参数,这样您也可以在那里访问按钮或鼠标的位置..
还请注意,使用MouseClick 事件而不是Click 事件更容易,因为它已经有了鼠标位置..
如果您需要/想要改用Click 事件,您可以跳过创建EventArgs,因为它没有有意义的数据;只需通过点击传递e..
Click 事件的启动方式如下:
private void Button1_Click(object sender, EventArgs e)
{
// we need the location of the clicked pixel:
Point clickLocation = Button1.PointToClient(Control.MousePosition);
// the rest can proceed as above, just with simple EventArgs..
如果您想检查所有鼠标单击事件并将它们中的每一个传递给父级,则必须对它们全部进行编码。
首先我们来看order of events on MSDN
- MouseDown 事件。
- 点击事件。
- 鼠标点击
- MouseUp 事件。
所以我们需要从MouseDown 开始。我们可以在辅助函数hitTest 中进行测试,所以我们可以重复使用它..:
Button clickedButton = null;
MouseEventArgs ee = null;
void hitTest(Button btn, MouseEventArgs e)
{
Size r = btn.BackgroundImage.Size;
// check that we have hit the image and hit a non-transparent pixel
if ((e.X < r.Width && e.Y < r.Height) &&
((Bitmap)btn.BackgroundImage).GetPixel(e.X, e.Y).A != 0)
{
clickedButton = btn;
ee = new MouseEventArgs(e.Button, e.Clicks, e.X + btn.Left, e.Y + btn.Top, e.Delta);
}
else clickedButton = null;
}
现在我们对所有四个事件进行编码。我们只需要调用一次hitTest,并在Click 事件中传递简单的、未修改的e 参数:
private void Button1_MouseDown(object sender, MouseEventArgs e)
{
hitTest(sender as Button, e);
if (sender != clickedButton)
yourParent_MouseDown((sender as Button).Parent, ee);
else // do your stuff
}
private void Button1_Click(object sender, EventArgs e)
{
if (sender != clickedButton)
yourParent_Click((sender as Button).Parent, e);
else // do your stuff
}
private void Button1_MouseClick(object sender, MouseEventArgs e)
{
if (sender != clickedButton)
yourParent_MouseClick((sender as Button).Parent, ee);
else // do your stuff
}
private void Button1_MouseUp(object sender, MouseEventArgs e)
{
if (sender != clickedButton)
yourParent_MouseUp((sender as Button).Parent, ee);
else // do your stuff
}
当然,您还需要为yourParent 编写所有四个事件..