Tôi gặp vấn đề về lỗi null với mã Jamie Dixon được đăng để tính đến tài khoản không có sự kiện Nhấp chuột.
private void RemoveClickEvent(Control control)
{
// chenged "FieldInfo f1 = typeof(Control)" to "var f1 = b.GetType()". By changing to
// the type of the passed in control we can use this for any control with a click event.
// using var allows for null checking and lowering the chance of exceptions.
var fi = control.GetType().GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
if (fi != null)
{
object obj = fi.GetValue(control);
PropertyInfo pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(control, null);
list.RemoveHandler(obj, list[obj]);
}
}
Sau đó, một thay đổi nhỏ và nó sẽ là cho bất kỳ sự kiện nào.
private void RemoveClickEvent(Control control, string theEvent)
{
// chenged "FieldInfo f1 = typeof(Control)" to "var f1 = b.GetType()". By changing to
// the type of the passed in control we can use this for any control with a click event.
// using var allows for null checking and lowering the chance of exceptions.
var fi = control.GetType().GetField(theEvent, BindingFlags.Static | BindingFlags.NonPublic);
if (fi != null)
{
object obj = fi.GetValue(control);
PropertyInfo pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(control, null);
list.RemoveHandler(obj, list[obj]);
}
}
Tôi tưởng tượng điều này có thể được thực hiện tốt hơn nhưng nó hoạt động cho nhu cầu hiện tại của tôi. Hy vọng điều này rất hữu ích cho ai đó.
Bạn có thể thay thế Nút bằng MyButtonClass không? –
Tôi nghĩ rằng cách dễ dàng hơn là vô hiệu hóa nút – V4Vendetta
Tôi muốn thêm chỉ một trình xử lý sự kiện sau đó để vô hiệu hóa sẽ không giúp ích gì. –