3
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?

René Vogt
  • 43,056
  • 14
  • 77
  • 99
LukAss741
  • 771
  • 1
  • 7
  • 24

2 Answers2

2

I don't see a way to do that.

As you can see in the reference source, LinkLabel is derived from Label. The Click event is raised by the Label base class. You can see in the code that the base methods like OnMouseDown and OnMouseUp are always called before the LinkLabel handles those events.

So the Label base implementation will always raise a Click event before the LinkClicked implementation raises the LinkLabel event. There is no property or flag to prevent that.

You hopefully can achieve what you want in a different way.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
2

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);
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • The cursor idea is simply great and does exactly what I wanted. Note that when you mark a link using tab on keyboard and press enter then only LinkClicked is called while if you click the link then both Click and LinkClicked are called. Thanks a lot. – LukAss741 May 15 '16 at 12:46
  • Ah, that's true. Thanks. – Hans Passant May 15 '16 at 12:54