.NET WinForms Custom Control: how to get a reference to the containing form

喜夏-厌秋 提交于 2019-12-24 05:07:02

问题


Is there a way, when creating a WinForms Custom Control/User Control, to get a reference at runtime to the form the control is placed on, so as to access various properties of that form? I would rather not pass a reference to the form into the constructor of the control, as, for various reasons, I need to keep a default constructor with no parameters.

One example: I have several Custom Controls that encapsulate Win32 API calls, and some of the calls require Window handles to be passed as parameters. I would like to be able to retrieve the handle of the containing form so I can pass it to the API function.

Another example: I have a Custom Control that provides "toast"-style user notifications. I would like to have the option of opening the notification form in a location relative to the location of the main application form, such as centered on the main window, off to the right, etc. This is not possible, obviously, without knowing the coordinates of the main application's window.

I could resort to using FindWindowEx()-type API calls in some cases, but that feels like a kludge, and would not work in all cases.

Does anyone know if this is possible?


回答1:


You can use Control.TopLevelControl property.




回答2:


You want Control.Parent, which returns the parent control. To get the form, simply call parent on all your parent controls until you hit a System.Windows.Forms.Form.




回答3:


Try the FindForm method. Be aware that it will return null if called in your control's constructor.

If you can wait until the OnParentChanged event, FindForm will return a reference to the parent form then.



来源:https://stackoverflow.com/questions/3783071/net-winforms-custom-control-how-to-get-a-reference-to-the-containing-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!