Search code examples
c#.netevent-handlingclicklinklabel

one click calls both Click and LinkClicked event handlers


LinkLabel label = new LinkLabel();
// imagine there is a code to initialize the label
label.Click += (sender, args) => callback1();
label.LinkClicked += (sender, args) => callback2();

If I click the label anywhere but not its link then callback1() is called which is correct.
If I click the label's link then both callback1() and callback2() are called.

How do I make it call callback2() only?


Solution

  • Two solutions I can think of. First one is a very silly one but looks pretty effective. You don't like Click when the mouse hovers over a link. Which has a side-effect, the mouse cursor changes. So you could filter by checking the cursor shape:

    private void linkLabel1_Click(object sender, EventArgs e) {
        if (Cursor.Current == Cursors.Default) {
           Debug.WriteLine("Click!");
           // etc...
        }
    }
    

    A bit more principled and handy if you have a lot of link labels is to not raise the Click event at all if the mouse is over a link. Add a new class to your project and paste this code:

    using System;
    using System.Windows.Forms;
    
    class LinkLabelEx : LinkLabel {
        protected override void OnClick(EventArgs e) {
            var loc = this.PointToClient(Cursor.Position);
            if (this.PointInLink(loc.X, loc.Y) == null) base.OnClick(e);
        }
    }