一次点击同时调用Click和LinkClicked事件处理程序

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

如果我点击标签而不是它的链接,那么会调用callback1(),这是正确的。
如果我点击标签的链接,则会调用callback1()callback2()
如何使其仅调用callback2()

use two separate labels. - M.kazem Akhgary
2个回答

2

我看不到有办法这样做。

如您在参考源代码中所看到的,LinkLabel是从Label派生的。 Click事件由Label基类引发。您可以在代码中看到,像OnMouseDownOnMouseUp这样的基本方法总是在LinkLabel处理这些事件之前调用。

因此,在LinkClicked实现引发LinkLabel事件之前,Label基础实现将始终引发Click事件。没有属性或标志可以防止这种情况。

希望您可以以不同的方式实现您想要的功能。


2

我可以想到两种解决方案。第一种非常愚蠢但看起来相当有效。您不喜欢在鼠标悬停在链接上时点击。这会产生一个副作用,鼠标指针会改变。因此,您可以通过检查光标形状进行过滤:

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

如果有许多链接标签,更有原则且方便的方法是,如果鼠标悬停在链接上,则根本不触发单击事件。将以下代码添加到项目中的新类中并粘贴即可:
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);
    }
}

光标的想法非常棒,正是我想要的。请注意,当您使用键盘上的Tab键标记链接并按Enter键时,只会调用LinkClicked,而如果您单击链接,则会同时调用Click和LinkClicked。非常感谢。 - LukAss741
啊,没错。谢谢。 - Hans Passant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接