Where do I find event declarations in Visual Studio

↘锁芯ラ 提交于 2020-03-04 02:40:28

问题


I know that VS will open an eventhandler stub by doubleclicking on an event. I found the underlying event declaration in InitializeComponent of the form on which the button is located.

this.buttonWorkOn.Click += new System.EventHandler(this.buttonWorkOn_Click);

Can I use this event declaration (of Visual Studio) and register another eventhandling method with it?

Upon instantiation of that other form its eventhandling method would need to register itself with the click event of the button on the main form.
I have no clue how to do that even though I have read quite a bit about delegates and events and in principle I do understand how it works.

Thank you


回答1:


If you right click on an event handler in the code editor and browse the definition you will find the way that it is declared, which you can then use in your own code.

For example, the declaration for a Button's Click event is:

    public event EventHandler Click;

You can add these yourself and use them from other places to respond to events in any class you create.

Here's a sample form with a single button (added via the designer) that when clicked will raise its own event:

public partial class Form1 : Form
{
    public event EventHandler ButtonClicked;

    private void RaiseButtonClicked()
    {
        if (ButtonClicked != null)
            ButtonClicked(this, EventArgs.Empty);
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        RaiseButtonClicked();
    }
}

In another class you can then add a handler to that:

public class Responder
{
    public Responder(Form1 form)
    {
        form.ButtonClicked += OnButtonClicked;
    }

    private void OnButtonClicked(object sender, EventArgs args)
    {
        MessageBox.Show("Button was clicked");
    }
}

Now every instance of the Responder class will tell you when the button is clicked on the form.




回答2:


By "Double clicking on an event", visual studio will generate an event handler for you. What you don't see is that visual studio also subscribes the generated event handler to the event, by adding a line of code in your designer file.

If goes something like this:

  • Double click 'clicked' event
  • Visual studio opens up your code file, and you have a new button1_clicked method, which is your event handler.
  • Your designer is updated with a line like button1.Clicked += button1_clicked

If you want to do manual event subscriptions, you can do so from your code file, by adding something like <formelement>.<event> += <eventhandler>. If you cant see available events in your intellisense, you can always check the online documentation. MSDN

(You should never change your designer file, as this is a generated file)




回答3:


If you like to get multiple methods been executed when an event occurs you can simply add all of them in your code (or you can even add the same method multiple times):

private void DoSomething(object source, EventArgs eventArgs)
{
    Console.WriteLine("Something happened.");
}

private void DoSomethingElse(object source, EventArgs eventArgs)
{
    Console.WriteLine("Something else happened.");
}

private void AttachToEvent()
{
    button1.Clicked += DoSomething;
    button1.Clicked += DoSomethingElse;
    button1.Clicked += DoSomething;
}

This would print out:

Something happened.

Something else happened.

Something happened.




回答4:


OK – it was not my application, I just tried to improve on it.
Anyway, the question was who owns whom and who is visible where.

On the Mainform are controls for user input.
On MainForm a variable of type "class preview" is declared:

Preview pv

For the Preview class I added an event declaration named WorkOn:

   public class Preview
    {
        #region "Variables"
        #region "PublicEvent"

        public event EventHandler WorkOn;
    }

Then in the MainForm, the variable pv – declared as a class field - is instantiated within a method.

pv = new Preview()

after which the user input in the controls of the main form is checked and when ok saved in the variables of the preview class.

Then, the PreviewForm is instantiated within the preview class, with the instance of the owning class (preview --> as instance pv) passed as a variable to the instantiation of the PreviewForm.
I had to create this overloaded constructor because from the PreviewForm an eventhandler must be registered with the preview class to make this work – as I realized.

formPreview formPreview = new formPreview(this);  

// this --> is the class preview, the instance pv

// Instantiation of FormPreview

  public formPreview(Preview preview)
    {
      InitializeComponent();

      this.preview = preview;
// now for the event in the preview class an eventhandling method 
// of the preview form is registered:  
      preview.WorkOn += formPreview_Close;
    }

This is the registered method of FormPreview:

   private void formPreview_Close(object sender, EventArgs e)
    {
        this.Close();
    }

I was reminded again that events can only be raised from the class that publishes the event. So I had to create a public event raising method within the class preview – here named OnWorkOn:

  public void OnWorkOn()
    {
        if (WorkOn != null)
            WorkOn(this, EventArgs.Empty);
    }

And finally I could trigger the event from the MainForm within the button to whose underlying event I planned to register the eventhandling method of the PreviewForm in the first place.
Only now I had to use the class variable pv of the MainForm as it is the medium between the MainForm and the PreviewForm:

public void buttonWorkOn_Click(object sender, EventArgs e)
{
    pv.OnWorkOn();  
// raising the event, informing whoever is registered to it
//...
}

So the design of the application did not allow for registering any eventhandling method of the preview form directly on the MainForm. That was the problem and I didn't quite see through the whole design yet.
Well – this is the outcome of a german C# tutorial – the only german one I know of.
You'll find it here:
[https://www.youtube.com/watch?v=-zCiwcgxMHw&list=PLvvL1HRuCBItyw45XnCqEXzuegKQd3MfL][1]
The code is not available for download anymore, but I could provide it as I am through.



来源:https://stackoverflow.com/questions/31534749/where-do-i-find-event-declarations-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!