WinForms equivalent of WPF's IsHitTestVisible

2020-02-01 17:51发布

I have a button override that has a Label as a child. I have MouseEnter and Leave events attached to the button control.

When the mouse enters the label the button's events are nullified (which is natural). My question is how can I disable the label's hit testing without actually disabling the label.

I want it to retain it's color and I want it to be able to change colors (MouseEnter on button for example), but when the mouse is over the label, the hit test to be considered on the button.

P.S: I know I can add Mouse Enter and Leave on the Label and handle those cases but I want the control to be self sufficient such that if the parameters change outside of it (the colors on mouse enter and leave), the control will still function properly.

2条回答
ら.Afraid
2楼-- · 2020-02-01 18:53

Ran across this question while looking for other information and don't believe the accepted answer is really correct.

You can extend the label and alter the hittest response in WndProc. Something along these lines:

public class HTTransparentLabel : Label
{
    private const int WM_NCHITTEST = 0x84; 
    private const int HTTRANSPARENT = -1; 

    protected override void WndProc(ref Message message) 
    { 
        if ( message.Msg == (int)WM_NCHITTEST ) 
            message.Result = (IntPtr)HTTRANSPARENT; 
        else 
            base.WndProc( ref message ); 
    }
}
查看更多
劫难
3楼-- · 2020-02-01 18:55

The short answer is that you cannot. Both the button and the label are in fact windows, so when the mouse leave one for the other, mouseenter and mouseleave events are generated.

The real question is, why do you need a label on a button?

查看更多
登录 后发表回答