-3
 this.FormClosing();

i want to Use C# windows form Event like a method but will say "the Event 'Form.FormClosing'can appear on the left hand side of += of -=".what should i do?!

  • Does this answer your question? [How to manually invoke an event?](https://stackoverflow.com/questions/8734700/how-to-manually-invoke-an-event) and [Calling an event handler in C#](https://stackoverflow.com/questions/12217632/calling-an-event-handler-in-c-sharp) and [event.Invoke(args) vs event(args). Which is faster?](https://stackoverflow.com/questions/5928077/event-invokeargs-vs-eventargs-which-is-faster) –  Aug 06 '21 at 05:22

1 Answers1

-1

I think you should provide a little more information about what you're trying to accomplish. What logic are you trying to run?

Essentially, Form.FormClosing (MSDN Form.FormClosing Event) is declared as an event, not a method. So in order to assign logic to run when that event occurs, you need to wire an event handler to it.

this.FormClosing += OnFormClosing;

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    // Logic to be performed as the form closes
}

See: How to add or remove an event handler

If you're trying to invoke the event outside of it's natural invocation path (ie when the form is closing), you can do try something like this:

if (this.FormClosing != null) this.FormClosing.Invoke(this, EventArgs.Empty);

// Or null shorthand:

this.FormClosing?.Invoke(this, EventArgs.Empty);

How to raise and consume events

But.. if you want to run the logic that would run with the window closes, you can just move it to its own method, and run that.

this.FormClosing += OnFormClosing;

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    MyWindowClosingLogic(true);
}

private void MyWindowClosingLogic(bool isClosing = false)
{
    if (!isClosing)
    {
        System.Diagnostics.Debug.WriteLine("The logic is being run, but the window is not closing...");
    }
    else 
    {
        System.Diagnostics.Debug.WriteLine("The Window is closing");
    }
}

private void SomeOtherMethod()
{
    MyWindowClosingLogic();
}
Andy Stagg
  • 373
  • 5
  • 22