How does EventArgs Cancel work in a FormClosing event?

How does the e.Cancel event work in the FormClosing event in WinForm? I know that you set it Trueto cancel the close, but at what point is this procedure being processed? Is there a secondary action taken by the property?

How can I implement a similar action in a user control? (C # or VB)

Note. I searched for about 30 minutes and could not find the answers on Google or the SO search, so if this is a duplicate, my bad one.

+3
source share
3 answers

, , , Cancel = false, Cancel = true. , " " .

, OR AND . Reflector, CancelEventArgs.Cancel, :

public bool Cancel
{
    get{ return this.cancel; }
    set{ this.cancel = value; }
}

, "Form.OnClosing(CancelEventArgs args)" , , , , Reflector:

[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnClosing(CancelEventArgs e)
{
    CancelEventHandler handler = (CancelEventHandler) base.Events[EVENT_CLOSING];
    if (handler != null)
    {
        handler(this, e);
    }
}

, , EVENT_CLOSING Events API , handler OnClosing null, Cancel = true, , CancelEventArgs.Cancel == true. EventHandlerList, :

get { 
    ListEntry e = null;
    if (parent == null || parent.CanRaiseEventsInternal) 
    {
        e = Find(key);
    }
    if (e != null) { 
        return e.handler;
    } 
    else { 
        return null;
    } 
}

parent.CanRaiseEventsInternal , .

... , , , , , . CancelEventHandler, CancelEventArgs.Cancel , true. , , Cancel = false Cancel = true. - ? - ?

public bool Cancel
{
   get{ return this.cancel; }
   set{ this.cancel = this.cancel || value; } 
}
+7

, Windows Forms:

public event CancelEventHandler MyEvent;

protected void OnMyEvent(CancelEventArgs e) {
  CancelEventHandler handler = MyEvent;
  if (handler != null) {
    handler(this, e);
  }
}

private void button1_Click(object sender, EventArgs e) {
  CancelEventArgs args = new CancelEventArgs();
  OnMyEvent(args);
  if (!args.Cancel) {
    // Client code didn't cancel, do your stuff
    //...
  }
}
+2
function OnMyCancelableEvent()
{
   var handler = CancelableEvent;
   var args = new CancelEventArgs()
   if(handler != null)
   {
        handler(this, args)
        if(args.Canceled)
           // do my cancel logic
        else
           // do stuff
   }
}
0

Source: https://habr.com/ru/post/1721596/


All Articles