透明度和鼠标事件WinForms

时间:2013-01-21 03:42:52

标签: c# winforms events transparency

我目前有一个具有完全透明背景的表单。目前,当用户将鼠标悬停在表单上的控件上时,我必须在论坛顶部显示图片框。

Screenshot!

将鼠标悬停在PictureBox上会正确触发MouseEnter事件,并将按钮Visible状态设置为true,MouseLeave事件将其设置为false。按钮本身具有相同的MouseEnterMouseLeave事件,但是Winforms将鼠标事件传递到表单上透明的任何空间下的表单(我在按钮中使用的图像也是透明的)每当我点击按钮时,它们就会消失,因为表格认为鼠标已经“左”了按钮或表格。有谁知道阻止事件传递的任何方式?

你问的一些代码?你得到的一些代码:)

// Form Constructor!
// map = picturebox, this = form, move = first button, attach = second button
public Detached(PictureBox map)
{
    InitializeComponent();
    doEvents(map, this, this.attach, this.move);
}

// doEvents method! I use this to add the event to all controls
// on the form!
void doEvents(params Control[] itm)
{
    Control[] ctls = this.Controls.Cast<Control>().Union(itm).ToArray();
    foreach (Control ctl in ctls)
    {
        ctl.MouseEnter += (s, o) =>
        {
            this.attach.Visible = true;
            this.move.Visible = true;
        };
        ctl.MouseLeave += (s, o) =>
        {
            this.attach.Visible = false;
            this.move.Visible = false;
        };
    }
}

1 个答案:

答案 0 :(得分:0)

感谢Hans Passant指出我正确的方向。我最终创建了一个线程,用于检查鼠标是否每隔50ms处于边界内。

public Detached(PictureBox map)
{
    Thread HoverCheck = new Thread(() =>
    {
        while (true)
        {
            if (this.Bounds.Contains(Cursor.Position))
            {
                ToggleButtons(true);
            }
            else
            {
                ToggleButtons(false);
            }
            Thread.Sleep(50);
        }
    });
    HoverCheck.Start();
}

void ToggleButtons(bool enable)
{
    if (InvokeRequired)
    {
        Invoke(new MethodInvoker(() => ToggleButtons(enable)));
        return;
    }

    this.attach.Visible = enable;
    this.move.Visible = enable;
    this.pictureBox1.Visible = enable;
}

谢谢:)