简体   繁体   English

如何提高MouseClick事件?

[英]How to raise MouseClick event?

Hello I have read that events can be raised the same way as methods. 您好我已经读过可以像方法一样引发事件。 Well it works for my custom events (I create a delegate, the event and I am able to raise the event by calling it). 它适用于我的自定义事件(我创建一个委托,事件,我可以通过调用它来引发事件)。 However I am not able to manually raise events like MouseClick and other, it keeps saying that it must appear on the left side of the += operator. 但是我无法手动引发像MouseClick等其他事件,它一直说它必须出现在+ =运算符的左侧。 What is the problem? 问题是什么?

While I am certain you'll get other answers more informative than this one, basically you can't "raise" an event outside the class that contains it. 虽然我确信你会得到比这个更有用的其他答案,但基本上你不能“提升”包含它的类之外的事件。 MSDN has this to say about events MSDN对事件有这个说法

Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the publisher class). 事件是一种特殊的多播委托, 只能从声明它们的类或结构 (发布者类)中调用 If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event. 如果其他类或结构订阅了该事件,则当发布者类引发该事件时,将调用它们的事件处理程序方法。

If you wanted to literally raise the event for, say, a Windows Forms Control MouseClick, you'd have to create a subclass of that control and either invoke base.OnMouseClick() or override it. 如果你想为Windows Forms Control MouseClick提升事件,你必须创建该控件的子类,并调用base.OnMouseClick()或覆盖它。

If this is a button, you can programmatically click it using the PerformClick method. 如果这是一个按钮,您可以使用PerformClick方法以编程方式单击它。

Sadly, this only works on buttons and not other types of Control s... except MenuItem . 可悲的是,这只适用于按钮而不是其他类型的Control ...除了MenuItem

If you want to click button you should call: 如果您想点击按钮,您应该致电:

button1.PerformClick();

If you want to call MouseClick please refer to this forum , there is solution in c# using windows api: 如果你想调用MouseClick请参考这个论坛 ,使用windows api在c#中有解决方案:

Let's say you want to manually raise the event "click". 假设你想手动提升事件“点击”。 This works for me: 这对我有用:

public partial class CustomButton : UserControl
{
    public new event EventHandler Click;

    private void lblText_Click(object sender, EventArgs e)
    {
        Click(this, e);
    }

}
private void button1_Click(object sender, EventArgs e)
{
    //Enter your code here
}

void Page_Load(object sender, EventArgs e){
    this.button1.Click += new System.EventHandler(this.button1_Click);

    this.button1_Click(this, e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM