简体   繁体   中英

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. 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

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.

If this is a button, you can programmatically click it using the PerformClick method.

Sadly, this only works on buttons and not other types of Control s... except 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:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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