“e.Cancel ” in formclosing Event

后端 未结 4 1666
谎友^
谎友^ 2021-02-04 11:21

When using the FormClosing event, why does the code e.Cancel = true; work, but new CancelEventArgs().Cancel = true; does not work?

4条回答
  •  Happy的楠姐
    2021-02-04 12:00

    It's because the CancelEventArgs is an object reference passed to the event handler in your code. The behind the scenes code raises FormClosing with a CancelEventArgs object and all the event handlers receive that same object. Once all the handlers have had their turn, the behind the scenes code checks the CancelEventArgs object it sent to see if its Cancel property is set to true. If it is, it doesn't do anything, and the FormClose chain of events stops. If Cancel is false (CancelEventArgs default value), meaning it hasn't been set to Cancel the chain of events, the behind the scenes code proceeds along, and then raises the FormClosed event.

    You can read more at Form.FormClosing Event on MSDN.

    In Forms all the -ing events are typically followed by an -ed event. The -ing events usually have CancelEventArgs, which can have its Cancel property set to true to stop the -ed event from happening.

提交回复
热议问题