Prevent next event handler being called

后端 未结 6 1211
孤街浪徒
孤街浪徒 2021-01-21 01:35

I have two event handlers wired up to a button click in a Windows form like so:

this.BtnCreate.Click += new System.EventHandler(new RdlcCreator().FirstHandler);
         


        
6条回答
  •  余生分开走
    2021-01-21 02:20

    Was finding the solution to the same question, but no luck. So had to resolve myself. A base class for Cancelable event args

    public class CancelableEventArgs
    {
        public bool Cancelled { get; set; }
        public void CancelFutherProcessing()
        {
            Cancelled = true;
        }
    }
    

    Next defines the extension method for the EventHandler, note that Invocation List subscribers invoked in backward order (in my case UI elements subscibe the event as they added to components, so which element is rendered later has most visiblility and more priority)

    public static class CommonExtensions
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void SafeInvokeWithCancel(this EventHandler handler, object sender, T args) where T : CancelableEventArgs
        {
            if (handler != null)
            {
                foreach (var d in handler.GetInvocationList().Reverse())
                {
                    d.DynamicInvoke(sender, args);
                    if (args.Cancelled)
                    {
                        break;
                    }
                }
            }
        }
    

    And here is the usage

    public class ChessboardEventArgs : CancelableEventArgs
    {
        public Vector2 Position { get; set; }
    }
    

    So if an UI element has some behaviour on the event, it cancells futher processing

            game.OnMouseLeftButtonDown += (sender, a) =>
            {
                var xy = GetChessboardPositionByScreenPosition(a.XY);
                if (IsInside(xy))
                {
                    var args = new ChessboardEventArgs { Position = xy };
                    OnMouseDown.SafeInvokeWithCancel(this, args);
                    a.CancelFutherProcessing();
                }
            };
    

提交回复
热议问题