How to trigger an Control.Resize event without act

2019-05-07 13:40发布

问题:

I'm not subclassing the control. Trying to trigger the event via Control.Size = Control.Size fails, since it does not trigger then even unless the new size is actually different.

回答1:

If you are subclassing Control, you can call OnResize directly, or expose it on the API:

 public void OnResize() {
     this.OnResize(EventArgs.Empty);
 }

However, you can't do this for arbitrary controls. You could change the Size to-and-fro? Alternatively, you could use reflection, but that is hacky:

 typeof (Control).GetMethod("OnResize",
     BindingFlags.Instance | BindingFlags.NonPublic)
     .Invoke(myControl, new object[] {EventArgs.Empty});


回答2:

I always do this by calling the Control's Resize event handler:

control_Resize(null, null);


回答3:

Why do you want to do this, and in what scenario? You can call OnResize, for example, when you're in the control itself (ie. in your derived control class). (Or via Reflection, when you are outside.)

Apart from that, you'll probably have to change the control's size, since that is what the Resize event is for :)



回答4:

Just change the size of the control using: Control.Size = new Size(x,y);

Changing the size of the control will issue a resize event for that control and the control should resize.

Alternatively if you just want to redraw the control then do: Control.Invalidate();