C# 如何在不实际调整大小的情况下触发 Control.Resize 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/515346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:23:54  来源:igfitidea点击:

How to trigger an Control.Resize event without actually resizing?

c#winformseventsresizecontrols

提问by mafu

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

我不是子类化控件。尝试通过Control.Size = Control.Size失败触发事件,因为即使新大小实际上不同,它也不会触发。

采纳答案by Marc Gravell

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

如果是子类化Control,可以OnResize直接调用,或者在 API 上公开:

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

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

但是,您不能对任意控件执行此操作。你可以改变Size来回?或者,您可以使用反射,但这是hacky:

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

回答by Calanus

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

只需使用以下方法更改控件的大小: 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();

或者,如果您只想重绘控件,请执行以下操作: Control.Invalidate();

回答by Fabian Schmied

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.)

你为什么要这样做,在什么情况下?例如,当您在控件本身中(即在您的派生控件类中)时,您可以调用 OnResize。(或者通过反射,当你在外面时。)

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

除此之外,您可能必须更改控件的大小,因为这是 Resize 事件的用途:)

回答by John Line

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

我总是通过调用控件的 Resize 事件处理程序来做到这一点:

control_Resize(null, null);