public void AddHandler_Getter_RemoveHandler_Getter_Roundtrips() { var list = new EventHandlerList(); // Create two different delegate instances Action a1 = () => Assert.True(false); Action a2 = () => Assert.False(true); Assert.NotSame(a1, a2); // Neither entry in the list has a delegate Assert.Null(list["key1"]); Assert.Null(list["key2"]); // Add the first delegate to the first entry list.AddHandler("key1", a1); Assert.Same(a1, list["key1"]); Assert.Null(list["key2"]); // Add the second delegate to the second entry list.AddHandler("key2", a2); Assert.Same(a1, list["key1"]); Assert.Same(a2, list["key2"]); // Then remove the first delegate list.RemoveHandler("key1", a1); Assert.Null(list["key1"]); Assert.Same(a2, list["key2"]); // And remove the second delegate list.RemoveHandler("key2", a2); Assert.Null(list["key1"]); Assert.Null(list["key2"]); }
public void Dispose_ClearsList() { var list = new EventHandlerList(); // Create two different delegate instances Action a1 = () => Assert.True(false); Action a2 = () => Assert.False(true); Assert.NotSame(a1, a2); // Neither entry in the list has a delegate Assert.Null(list["key1"]); Assert.Null(list["key2"]); for (int i = 0; i < 2; i++) { // Add the delegates list.AddHandler("key1", a1); list.AddHandler("key2", a2); Assert.Same(a1, list["key1"]); Assert.Same(a2, list["key2"]); // Dispose to clear the list list.Dispose(); Assert.Null(list["key1"]); Assert.Null(list["key2"]); // List is still usable, though, so loop around to do it again } }
public void AddHandler_MultipleInSameKey_Getter_CombinedDelegates() { var list = new EventHandlerList(); // Create two delegates that will increase total by different amounts int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add both delegates for the same key and make sure we get them both out of the indexer list.AddHandler("key1", a1); list.AddHandler("key1", a2); list["key1"].DynamicInvoke(); Assert.Equal(3, total); // Remove the first delegate and make sure the second delegate can still be retrieved list.RemoveHandler("key1", a1); list["key1"].DynamicInvoke(); Assert.Equal(5, total); // Remove a delegate that was never in the list; nop list.RemoveHandler("key1", new Action(() => { })); list["key1"].DynamicInvoke(); Assert.Equal(7, total); // Then remove the second delegate list.RemoveHandler("key1", a2); Assert.Null(list["key1"]); }
public void AddHandler_RemoveHandler_Roundtrips() { var list = new EventHandlerList(); Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // Add the first delegate to the first entry. list.AddHandler("key1", action1); Assert.Same(action1, list["key1"]); Assert.Null(list["key2"]); // Add the second delegate to the second entry. list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Then remove the first delegate. list.RemoveHandler("key1", action1); Assert.Null(list["key1"]); Assert.Same(action2, list["key2"]); // And remove the second delegate. list.RemoveHandler("key2", action2); Assert.Null(list["key1"]); Assert.Null(list["key2"]); }
public static void BindingEvents(Control src, Control dst) { if (src == null) { throw new ArgumentNullException(nameof(src)); } if (dst == null) { throw new ArgumentNullException(nameof(dst)); } Type t = typeof(Control); EventHandlerList srcEvents = (EventHandlerList)t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(src); EventHandlerList dstEvents = (EventHandlerList)t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(dst); foreach (EventInfo eventInfo in t.GetEvents(BindingFlags.Public | BindingFlags.Instance)) { if (eventInfo.Name == "Disposed" || eventInfo.Name == "EventControlAdded") { continue; } FieldInfo fieldInfo = t.GetField("Event" + eventInfo.Name, BindingFlags.NonPublic | BindingFlags.Static) ?? t.GetField("Event" + _suffixReg.Replace(eventInfo.Name, ""), BindingFlags.NonPublic | BindingFlags.Static); //winforms ♥ object field = fieldInfo.GetValue(null); HandlerRouter router = new HandlerRouter(field, dstEvents, dst, src, eventInfo.Name); MethodInfo handlerInfo = router.GetType().GetMethod("Invoke", new Type[] { typeof(object), typeof(EventArgs) }); Delegate deleg = Delegate.CreateDelegate(eventInfo.EventHandlerType, router, handlerInfo, true); //надо создать делегат задано сигнатуры //Delegate combine = Delegate.Combine(deleg, dstEvents[field]); srcEvents.AddHandler(field, deleg); //eventInfo.AddEventHandler(src, deleg); } }
public static void BindingConcreteEvents(this Control src, Control dst) { if (src == null) { throw new ArgumentNullException(nameof(src)); } if (dst == null) { throw new ArgumentNullException(nameof(dst)); } Type t = typeof(Control); EventHandlerList srcEvents = (EventHandlerList)t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(src); EventHandlerList dstEvents = (EventHandlerList)t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(dst); string[] eventNames = { "MouseMove", "MouseDown", "MouseClick", "MouseUp", "MouseCaptureChanged", "KeyDown", "KeyPress", "KeyUp" }; foreach (EventInfo eventInfo in t.GetEvents(BindingFlags.Public | BindingFlags.Instance).Where(e => eventNames.Contains(e.Name))) { FieldInfo fieldInfo = t.GetField("Event" + eventInfo.Name, BindingFlags.NonPublic | BindingFlags.Static) ?? t.GetField("Event" + _suffixReg.Replace(eventInfo.Name, ""), BindingFlags.NonPublic | BindingFlags.Static); object field = fieldInfo.GetValue(null); if (src.Parent != null && (srcEvents[field]?.GetInvocationList().Any(d => (d.Target as HandlerRouter)?.Destination == src.Parent) ?? false)) { return; } HandlerRouter router = new HandlerRouter(field, dstEvents, dst, src, eventInfo.Name); MethodInfo handlerInfo = router.GetType().GetMethod("Invoke", new Type[] { typeof(object), typeof(EventArgs) }); Delegate deleg = Delegate.CreateDelegate(eventInfo.EventHandlerType, router, handlerInfo, true); srcEvents.AddHandler(field, deleg); } }
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler) { lock (eventHandlersLock) { eventHandlers.AddHandler(CanonicalizeSectionName(sectionName), handler); } }
public IHttpActionResult EventHandlerList() { EventHandlerList eventHandlers = new EventHandlerList(); eventHandlers.AddHandler("StringProcessorDelegate", x); return(Json(eventHandlers)); }
public override void OnInvoke(InvocationContext context) { Console.WriteLine(context.Method); MethodInfo method = context.Method as MethodInfo; if (method.IsSpecialName) { if (method.Name.StartsWith("add_")) { string name = method.Name.Replace("add_", ""); object key = GetHandlerKey(name); handlers.AddHandler(key, context.Arguments[0] as Delegate); OnAddHandler(context, name, key); } else if (method.Name.StartsWith("remove_")) { string name = method.Name.Replace("remove_", ""); object key = GetHandlerKey(name); handlers.RemoveHandler(key, context.Arguments[0] as Delegate); OnRemoveHandler(context, name, key); } } else { OnInvokeMethod(context); } }
public void RenderCalendar_RenderLevelIsGreateThenOneAndUserSelectorIsFalse_ReturnsCalenderHtmlContent() { // Arrange _calendar = CreateCalendarObject(); _calendar.SelectedDate = DateTime.MinValue; _calendar.Enabled = false; _privateObject = new PrivateObject(_calendar); var stringWriter = new StringWriter(); var output = new HtmlTextWriter(stringWriter); _privateObject.SetFieldOrProperty("_autoPostBack", true); ShimControl.AllInstances.EventsGet = (x) => { var eventHandlerList = new EventHandlerList(); CalculationHandler sumHandler = new CalculationHandler(Sum); eventHandlerList.AddHandler("click", sumHandler); return(eventHandlerList); }; // Act _privateObject.Invoke(RenderCalendar, output); // Assert output.ShouldSatisfyAllConditions( () => output.ShouldNotBeNull(), () => output.InnerWriter.ShouldNotBeNull() ); }
public void Resume(string pMethodName) { //if (_handlers == null) // throw new ApplicationException("Events have not been suppressed."); Dictionary <object, Delegate[]> toRemove = new Dictionary <object, Delegate[]>(); // goes through all handlers which have been suppressed. If we are resuming, // all handlers, or if we find the matching handler, add it back to the // control's event handlers foreach (KeyValuePair <object, Delegate[]> pair in suppressedHandlers) { for (int x = 0; x < pair.Value.Length; x++) { string methodName = pair.Value[x].Method.Name; if (pMethodName == null || methodName.Equals(pMethodName)) { _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]); toRemove.Add(pair.Key, pair.Value); } } } // remove all un-suppressed handlers from the list of suppressed handlers foreach (KeyValuePair <object, Delegate[]> pair in toRemove) { for (int x = 0; x < pair.Value.Length; x++) { suppressedHandlers.Remove(pair.Key); } } //_handlers = null; }
void AddEventHandler(object key, EventHandler handler) { if (events == null) { events = new EventHandlerList(); } events.AddHandler(key, handler); }
/// <summary> /// 增加代理 /// </summary> /// <param name="value"></param> public void AddHandler(TResponseType rspType, Delegate value) { if (value != null) { string key = rspType.ToString(); events.AddHandler(key, value); } }
private void AddPropertyChanged(DependencyObjectType type, DependencyPropertyChangedEventHandler handler) { if (type != doType && !type.IsSubclassOf(doType)) { throw new ArgumentException(); } handlers.AddHandler(type, handler); }
/// <summary> /// Raises 'Method' action when SymbolPath value changes /// </summary> /// <param name="SymbolName">Path of Symbol to poll for value change</param> /// <param name="Method">Action / method executed on value change</param> public void SubscribeOnValueChange(string SymbolPath, Action <object> Method) { if (_dynamicEvents[SymbolPath] == null) { IValueSymbol symbol = (IValueSymbol)_symbolLoader.Symbols[SymbolPath]; symbol.ValueChanged += Symbol_ValueChanged; _dynamicEvents.AddHandler(symbol.InstancePath, Method); } }
public void AddHandlers_Gettable() { var list1 = new EventHandlerList(); var list2 = new EventHandlerList(); int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add the delegates to separate keys in the first list list1.AddHandler("key1", a1); list1.AddHandler("key2", a2); // Then add the first list to the second list2.AddHandlers(list1); // And make sure they contain the same entries Assert.Same(list1["key1"], list2["key1"]); Assert.Same(list1["key2"], list2["key2"]); }
public static bool Subscribe(string eventName, EventHandler handler) { if (m_eventList != null) { lock (m_eventList) { m_eventList.AddHandler(eventName, handler); } return(true); } return(false); }
public static void AddEventDelegates(this Control _Target, string _Event, Delegate[] _Delegates) { FieldInfo f1 = typeof(Control).GetField("Event" + _Event, BindingFlags.Static | BindingFlags.NonPublic); object obj = f1.GetValue(_Target); PropertyInfo pi = _Target.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList list = (EventHandlerList)pi.GetValue(_Target, null); foreach (var currDelegate in _Delegates) { list.AddHandler(obj, currDelegate); } }
/// <summary> /// 增加代理 /// </summary> /// <param name="value"></param> public void AddHandler(TResponseType rspType, Delegate value) { if (value != null) { string key = rspType.ToString(); events.AddHandler(key, value); if (!eventsDataList.ContainsKey(key)) { eventsDataList.Add(key, value); } } }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //생성 : //추가 : //목적 : 기존 버튼 클릭 이벤트 지우고 시작 이벤트 -> 실제 클릭 이벤트 -> 종료 이벤트로 변경해줌 //설명 : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void SetButtonEventChange(Control obj) { // 메서드 정보를 가져옴 MethodInfo objMethod = this.GetType().GetMethod("get_Events", BindingFlags.NonPublic | BindingFlags.Instance); // 메서드 정보와 인스턴스를 통해 이벤트 핸들러 목록을 가져옴 EventHandlerList objEventList = objMethod.Invoke(obj, new object[] { }) as EventHandlerList; // 해당 버튼 클래스에 Control Type을 가져옴 Type objControlType = GetControlType(obj.GetType()); // 필드 정보를 가져옴 FieldInfo objFieldInfo = objControlType.GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static); // 필드 정보에서 해당 컨트롤을 지원하는 필드값을 가져옴 object objClickValue = objFieldInfo.GetValue(obj); // 등록된 델리게이트 이벤트를 가져옴 Delegate delegateButtonClick = objEventList[objClickValue]; // 기존 클릭 이벤트를 지우고 시작 이벤트 -> 실 구현 이벤트 -> 종료 이벤트로 변경해줌 objEventList.RemoveHandler(objClickValue, delegateButtonClick); objEventList.AddHandler(objClickValue, new EventHandler(SetButtonStartLog)); objEventList.AddHandler(objClickValue, delegateButtonClick); objEventList.AddHandler(objClickValue, new EventHandler(SetButtonEndLog)); }
public void NullKey() { EventHandlerList list = new EventHandlerList(); EventHandler one = new EventHandler(Deleg1); list.AddHandler(null, one); EventHandler d = list [null] as EventHandler; Assert.IsNotNull(d, "NullKey #01"); list.RemoveHandler(null, one); d = list [null] as EventHandler; Assert.IsNull(d, "NullKey #02"); }
public void NullKey() { EventHandlerList list = new EventHandlerList(); EventHandler one = new EventHandler(Deleg1); list.AddHandler(null, one); EventHandler d = list [null] as EventHandler; Assertion.Assert("NullKey #01", d != null); list.RemoveHandler(null, one); d = list [null] as EventHandler; Assertion.Assert("NullKey #02", d == null); }
public void Dispose_ClearsList() { var list = new EventHandlerList(); // Create two different delegate instances. Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // The list is still usable after disposal. for (int i = 0; i < 2; i++) { // Add the delegates list.AddHandler("key1", action1); list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Dispose to clear the list. list.Dispose(); Assert.Null(list["key1"]); Assert.Null(list["key2"]); } }
public void WatchUnityEvent(UnityEventType type, Action action) { if (!eventCallers.ContainsKey(type)) { var newCaller = new EventHandlerList(); newCaller.AddHandler(action); eventCallers.Add(type, newCaller); } else { var caller = eventCallers[type]; caller.AddHandler(action); } }
/// <summary> /// /// </summary> /// <param name="getParameter"></param> /// <param name="handler"></param> public void AddChangeHandler(IConfigParameter getParameter, ConfigChangedEventHandler handler) { ConfigChangedEventHandler callback = eventHandles[getParameter.GroupName] as ConfigChangedEventHandler; if (callback == null) { lock (eventHandlersLock) { callback = eventHandles[getParameter.GroupName] as ConfigChangedEventHandler; if (callback == null) { eventHandles.AddHandler(getParameter.GroupName, handler); } } } }
public void Resume() { if (_handlers == null) { throw new ApplicationException("Events have not been suppressed."); } foreach (KeyValuePair <object, Delegate[]> pair in _handlers) { for (int x = 0; x < pair.Value.Length; x++) { _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]); } } _handlers = null; }
public Form1() { InitializeComponent(); button1.Click += new EventHandler(button1_Click); // Get secret click event key FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static); object secret = eventClick.GetValue(null); // Retrieve the click event PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList events = (EventHandlerList)eventsProp.GetValue(button1, null); Delegate click = events[secret]; // Remove it from button1, add it to button2 events.RemoveHandler(secret, click); events = (EventHandlerList)eventsProp.GetValue(button2, null); events.AddHandler(secret, click); }
private object DoMethodCallInternal(MethodInfo method, object[] parameters) { Type retType = method.ReturnType; if (retType == typeof(string)) { return("some string"); } else if (retType == typeof(int)) { return(32242); } if (method.IsSpecialName) { int opId = -1; string name = null; string[] specialOperations = new string[] { "add_", "remove_" }; for (int i = 0; i < specialOperations.Length; i++) { string prefix = specialOperations[i]; if (method.Name.StartsWith(prefix)) { name = method.Name.Substring(prefix.Length); opId = i; break; } } switch (opId) { case 0: // Add Event Handler eventHandlerList.AddHandler(name, parameters[0] as Delegate); return(null); case 1: // Remove Event Handler eventHandlerList.RemoveHandler(name, parameters[0] as Delegate); return(null); } } // Default operation return(remoteCaller.Call(this, method, parameters)); }
/// <summary> /// Adds a handler to the specified event. /// </summary> /// <param name="key"> /// The event key. /// </param> /// <param name="value"> /// The event handler delegate. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="key"/> is <see langword="null"/></para> /// <para>-or-</para> /// <para><paramref name="value"/> is <see langword="null"/></para> /// </exception> internal void AddEventHandler(object key, Delegate value) { if (null == key) { throw new ArgumentNullException("key"); } if (null == value) { throw new ArgumentNullException("value"); } lock (this) { if (null == _events) { _events = new EventHandlerList(); } _events.AddHandler(key, value); } }
/// <summary> /// 订阅事件 /// </summary> /// <param name="handler"></param> /// <param name="key"></param> public void Subscribe(EventHandler <T> handler, string key) { Handlers.AddHandler(key, handler); }