Control. Controls Свойство
Определение
Возвращает коллекцию элементов управления, содержащихся в элементе управления. Gets the collection of controls contained within the control.
Значение свойства
Объект Control.ControlCollection представляет коллекцию элементов управления, содержащихся в элементе управления. A Control.ControlCollection representing the collection of controls contained within the control.
Примеры
В следующем примере кода удаляется Control из Control.ControlCollection производного класса, Panel если он является членом коллекции. The following code example removes a Control from the Control.ControlCollection of the derived class Panel if it is a member of the collection. В этом примере необходимо создать, Panel Button и хотя бы один RadioButton элемент управления в Form . The example requires that you have created a Panel, a Button, and at least one RadioButton control on a Form. RadioButtonЭлементы управления добавляются в Panel элемент управления, а Panel элемент управления добавляется в Form . The RadioButton control(s) are added to the Panel control, and the Panel control added to the Form. При нажатии кнопки переключатель removeButton удаляется из Control.ControlCollection . When the button is clicked, the radio button named removeButton is removed from the Control.ControlCollection.
Комментарии
ControlМожет действовать как родительская коллекция элементов управления. A Control can act as a parent to a collection of controls. Например, при добавлении нескольких элементов управления в Form каждый из элементов управления является членом объекта, Control.ControlCollection присвоенного Controls свойству формы, который является производным от Control класса. For example, when several controls are added to a Form, each of the controls is a member of the Control.ControlCollection assigned to the Controls property of the form, which is derived from the Control class.
Управлять элементами управления в Control.ControlCollection назначенном Controls свойстве можно с помощью методов, доступных в Control.ControlCollection классе. You can manipulate the controls in the Control.ControlCollection assigned to the Controls property by using the methods available in the Control.ControlCollection class.
При добавлении нескольких элементов управления в родительский элемент управления рекомендуется вызывать SuspendLayout метод перед инициализацией добавляемых элементов управления. When adding several controls to a parent control, it is recommended that you call the SuspendLayout method before initializing the controls to be added. После добавления элементов управления в родительский элемент управления вызовите ResumeLayout метод. After adding the controls to the parent control, call the ResumeLayout method. Это повысит производительность приложений с большим количеством элементов управления. Doing so will increase the performance of applications with many controls.
Используйте Controls свойство для прохода по всем элементам управления формы, включая вложенные элементы управления. Use the Controls property to iterate through all controls of a form, including nested controls. Используйте GetNextControl метод для получения предыдущего или следующего дочернего элемента управления в последовательности табуляции. Use the GetNextControl method to retrieve the previous or next child control in the tab order. Используйте ActiveControl свойство, чтобы получить или задать активный элемент управления контейнера. Use the ActiveControl property to get or set the active control of a container control.
Get a Windows Forms control by name in C#
I have a ToolStripMenuItem called myMenu . How can I access this like so:
This is because I am dynamically generating ToolStripMenuItems from an XML file and need to reference MenuItems by their dynamically generated names.
14 Answers 14
Disregard this, I reinvent wheels.
Assuming you have the menuStrip object and the menu is only one level deep, use:
For deeper menu levels add more SelectMany operators in the statement.
if you want to search all menu items in the strip then use
However, make sure each menu has a different name to avoid exception thrown by key duplicates.
To avoid exceptions you could use FirstOrDefault instead of SingleOrDefault / Single , or just return a sequence if you might have Name duplicates.
this.Controls.Find(name, searchAllChildren) doesn’t find ToolStripItem because ToolStripItem is not a Control
Using the same approach of Philip Wallace, we can do like this:
One of the best way is a single row of code like this:
In this example we search all PictureBox by name in a form
Most important is the second paramenter of find .
if you are certain that the control name exists you can directly use it:
Since you’re generating them dynamically, keep a map between a string and the menu item, that will allow fast retrieval.
This is the actual code that is ran:
Assuming you have Windows.Form Form1 as the parent form which owns the menu you’ve created. One of the form’s attributes is named .Menu . If the menu was created programmatically, it should be the same, and it would be recognized as a menu and placed in the Menu attribute of the Form.
In this case, I had a main menu called File . A sub menu, called a MenuItem under File contained the tag Open and was named menu_File_Open . The following worked. Assuming you
Have a look at the ToolStrip.Items collection. It even has a find method available.
You can do the following:
A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:
So now you have your iterator, child , which is of type Control . Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:
You can use find function in your Form class. If you want to cast (Label) ,(TextView) . etc, in this way you can use special features of objects. It will be return Label object.
name: item name of searched item in the form
true: Search all Children boolean value
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Control Class
Definition
Defines the base class for controls, which are components with visual representation.
Remarks
To create your own control class, inherit from the UserControl, Control classes, or from the other Windows Forms provided controls. For more information about authoring custom controls, see Developing Custom Windows Forms Controls with the .NET Framework.
The Control class implements very basic functionality required by classes that display information to the user. It handles user input through the keyboard and pointing devices. It handles message routing and security. It defines the bounds of a control (its position and size), although it does not implement painting. It provides a window handle ( hWnd ).
Windows Forms controls use ambient properties so child controls can appear like their surrounding environment. An ambient property is a control property that, if not set, is retrieved from the parent control. If the control does not have a Parent, and the property is not set, the control attempts to determine the value of the ambient property through the Site property. If the control is not sited, if the site does not support ambient properties, or if the property is not set on the AmbientProperties, the control uses its own default values. Typically, an ambient property represents a characteristic of a control, such as BackColor, that is communicated to a child control. For example, a Button will have the same BackColor as its parent Form by default. Ambient properties provided by the Control class include: Cursor, Font, BackColor, ForeColor, and RightToLeft.
To make your Windows Forms application support visual styles, be sure to set the FlatStyle property to System and include a manifest with your executable. A manifest is an XML file that is included either as a resource within your application executable or as a separate file that resides in the same directory as the executable file. For an example of a manifest, see the Example section of the FlatStyle enumeration. For more information about using visual styles, see Visual Styles.
Windows Forms has accessibility support built in, and provides information about your application that enables it to work with accessibility client applications such as screen enlarger and reviewer utilities, voice input utilities, on-screen keyboards, alternative input devices, and keyboard enhancement utilities. Sometimes you will want to provide additional information to accessibility client applications. There are two ways of providing this additional information. You can set the AccessibleName, AccessibleDescription, AccessibleDefaultActionDescription, and AccessibleRole property values, which will be reported to accessibility client applications. This method is typically used to provide limited accessibility information for existing controls. Alternatively, you can write your own class deriving from the AccessibleObject or Control.ControlAccessibleObject classes, providing as much accessibility information as needed.
To maintain better performance, do not set the size of a control in its constructor. The preferred method is to override the DefaultSize property.
Do not add data bindings for a Control in its constructor. Doing so will cause errors in code generation and can cause unwanted behavior.
The majority of the controls in the System.Windows.Forms namespace use the underlying Windows common control as a base to build on. For more information about the Windows common controls, see General Control Reference.
To identify Windows Forms controls from a separate process, use a standard SendMessage call to pass the WM_GETCONTROLNAME message. WM_GETCONTROLNAME is independent of the language and Windows hierarchy. For more information, see the «Recommended Solution for Windows Forms» topic in Automating Windows Forms.
Use the InvokeRequired property to synchronize access to the control from multiple threads. For more information about multithreaded Windows Forms controls, see How to: Make Thread-Safe Calls to Windows Forms Controls
Constructors
Initializes a new instance of the Control class with default settings.
Initializes a new instance of the Control class as a child control, with specific text.
Initializes a new instance of the Control class as a child control, with specific text, size, and location.
Initializes a new instance of the Control class with specific text.
Initializes a new instance of the Control class with specific text, size, and location.
Properties
Gets the AccessibleObject assigned to the control.
Gets or sets the default action description of the control for use by accessibility client applications.
Gets or sets the description of the control used by accessibility client applications.
Gets or sets the name of the control used by accessibility client applications.
Gets or sets the accessible role of the control.
Gets or sets a value indicating whether the control can accept data that the user drags onto it.
Gets or sets the edges of the container to which a control is bound and determines how a control is resized with its parent.
Gets or sets where this control is scrolled to in ScrollControlIntoView(Control).
This property is not relevant for this class.
Gets or sets the background color for the control.
Gets or sets the background image displayed in the control.
Gets or sets the background image layout as defined in the ImageLayout enumeration.
Gets or sets the BindingContext for the control.
Gets the distance, in pixels, between the bottom edge of the control and the top edge of its container’s client area.
Gets or sets the size and location of the control including its nonclient elements, in pixels, relative to the parent control.
Gets a value indicating whether the ImeMode property can be set to an active value, to enable IME support.
Gets a value indicating whether the control can receive focus.
Determines if events can be raised on the control.
Gets a value indicating whether the component can raise an event.
(Inherited from Component)
Gets a value indicating whether the control can be selected.
Gets or sets a value indicating whether the control has captured the mouse.
Gets or sets a value indicating whether the control causes validation to be performed on any controls that require validation when it receives focus.
Gets or sets a value indicating whether to catch calls on the wrong thread that access a control’s Handle property when an application is being debugged.
Gets the rectangle that represents the client area of the control.
Gets or sets the height and width of the client area of the control.
Gets the name of the company or creator of the application containing the control.
Gets the IContainer that contains the Component.
(Inherited from Component)
Gets a value indicating whether the control, or one of its child controls, currently has the input focus.
Gets or sets the shortcut menu associated with the control.
Gets or sets the ContextMenuStrip associated with this control.
Gets the collection of controls contained within the control.
Gets a value indicating whether the control has been created.
Gets the required creation parameters when the control handle is created.
Gets or sets the cursor that is displayed when the mouse pointer is over the control.
Gets the data bindings for the control.
Gets the default background color of the control.
Gets or sets the default cursor for the control.
Gets the default font of the control.
Gets the default foreground color of the control.
Gets the default Input Method Editor (IME) mode supported by the control.
Gets the space, in pixels, that is specified by default between controls.
Gets the length and height, in pixels, that is specified as the default maximum size of a control.
Gets the length and height, in pixels, that is specified as the default minimum size of a control.
Gets the internal spacing, in pixels, of the contents of a control.
Gets the default size of the control.
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Gets the DPI value for the display device where the control is currently being displayed.
Gets the rectangle that represents the display area of the control.
Gets a value indicating whether the base Control class is in the process of disposing.
Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.
Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.
Gets or sets a value indicating whether the control can respond to user interaction.
Gets the list of event handlers that are attached to this Component.
(Inherited from Component)
Gets a value indicating whether the control has input focus.
Gets or sets the font of the text displayed by the control.
Gets or sets the height of the font of the control.
Gets or sets the foreground color of the control.
Gets the window handle that the control is bound to.
Gets a value indicating whether the control contains one or more child controls.
Gets or sets the height of the control.
Gets or sets the Input Method Editor (IME) mode of the control.
Gets or sets the IME mode of a control.
Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.
Gets or sets a value indicating whether the control is visible to accessibility applications.
Gets a value indicating whether the control has been disposed of.
Gets a value indicating whether the control has a handle associated with it.
Gets a value indicating whether the control is mirrored.
Gets a cached instance of the control’s layout engine.
Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its container’s client area.
Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container.
Gets or sets the space between controls.
Gets or sets the size that is the upper limit that GetPreferredSize(Size) can specify.
Gets or sets the size that is the lower limit that GetPreferredSize(Size) can specify.
Gets a value indicating which of the modifier keys (SHIFT, CTRL, and ALT) is in a pressed state.
Gets a value indicating which of the mouse buttons is in a pressed state.
Gets the position of the mouse cursor in screen coordinates.
Gets or sets the name of the control.
Gets or sets padding within the control.
Gets or sets the parent container of the control.
Gets the size of a rectangular area into which the control can fit.
Gets the product name of the assembly containing the control.
Gets the version of the assembly containing the control.
Gets an object that represents a propagating IME mode.
Gets a value indicating whether the control is currently re-creating its handle.
Gets or sets the window region associated with the control.
This property is now obsolete.
Gets or sets a value indicating whether the control redraws itself when resized.
Gets the distance, in pixels, between the right edge of the control and the left edge of its container’s client area.
Gets or sets a value indicating whether control’s elements are aligned to support locales using right-to-left fonts.
Gets a value that determines the scaling of child controls.
Gets a value indicating whether the control should display focus rectangles.
Gets a value indicating whether the user interface is in the appropriate state to show or hide keyboard accelerators.
Gets or sets the site of the control.
Gets or sets the height and width of the control.
Gets or sets the tab order of the control within its container.
Gets or sets a value indicating whether the user can give the focus to this control using the TAB key.
Gets or sets the object that contains data about the control.
Gets or sets the text associated with this control.
Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its container’s client area.
Gets the parent control that is not parented by another Windows Forms control. Typically, this is the outermost Form that the control is contained in.
Gets or sets a value indicating whether to use the wait cursor for the current control and all child controls.
Gets or sets a value indicating whether the control and all its child controls are displayed.
Gets or sets the width of the control.
This property is not relevant for this class.
Methods
Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control.
Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control .
Executes the specified delegate asynchronously on the thread that the control’s underlying handle was created on.
Executes the specified delegate asynchronously with the specified arguments, on the thread that the control’s underlying handle was created on.
Brings the control to the front of the z-order.
Retrieves a value indicating whether the specified control is a child of the control.
Creates a new accessibility object for the control.
Forces the creation of the visible control, including the creation of the handle and any visible child controls.
Creates a new instance of the control collection for the control.
Creates the Graphics for the control.
Creates a handle for the control.
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Sends the specified message to the default window procedure.
Destroys the handle associated with the control.
Releases all resources used by the Component.
(Inherited from Component)
Releases the unmanaged resources used by the Control and its child controls and optionally releases the managed resources.
Begins a drag-and-drop operation.
Supports rendering to the specified bitmap.
Retrieves the return value of the asynchronous operation represented by the IAsyncResult passed.
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Retrieves the form that the control is on.
Sets input focus to the control.
Retrieves the control that contains the specified handle.
Returns the control that is currently associated with the specified handle.
Retrieves the specified AccessibleObject.
Retrieves a value indicating how a control will behave when its AutoSize property is enabled.
Retrieves the child control that is located at the specified coordinates.
Retrieves the child control that is located at the specified coordinates, specifying whether to ignore child controls of a certain type.
Returns the next ContainerControl up the control’s chain of parent controls.
Serves as the default hash function.
(Inherited from Object)
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Retrieves the next control forward or back in the tab order of child controls.
Retrieves the size of a rectangular area into which a control can be fitted.
Retrieves the bounds within which the control is scaled.
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Retrieves the value of the specified control style bit for the control.
Determines if the control is a top-level control.
Gets the Type of the current instance.
(Inherited from Object)
Conceals the control from the user.
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Called after the control has been added to another container.
Invalidates the entire surface of the control and causes the control to be redrawn.
Invalidates a specific region of the control and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.
Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control.
Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.
Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control.
Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.
Executes the specified delegate on the thread that owns the control’s underlying window handle.
Executes the specified delegate, on the thread that owns the control’s underlying window handle, with the specified list of arguments.
Raises the GotFocus event for the specified control.
Raises the LostFocus event for the specified control.
Raises the Click event for the specified control.
Raises the Paint event for the specified control.
Raises the PaintBackground event for the specified control.
Determines if a character is an input character that the control recognizes.
Determines whether the specified key is a regular input key or a special key that requires preprocessing.
Determines whether the CAPS LOCK, NUM LOCK, or SCROLL LOCK key is in effect.
Determines if the specified character is the mnemonic character assigned to the control in the specified string.
Converts a Logical DPI value to its equivalent DeviceUnit DPI value.
Transforms a size from logical to device units by scaling it for the current DPI and rounding down to the nearest integer value for width and height.
Creates a shallow copy of the current Object.
(Inherited from Object)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Raises the Invalidated event with a specified region of the control to invalidate.