Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Z-order of a Control using WinForms

I'm writing a custom TextBox that upon gaining focus changes its border style.

As adding a border causes the control to overlap with those neighbouring it, I temporarily bring the text box to the front of the dialog (using textBox.BringToFront()).

However, once editing is complete and focus is lost, I would like to send the control back to its original position in the Z-order.

Is this possible (preferably in a simple way!)

like image 838
g t Avatar asked Jul 09 '10 13:07

g t


People also ask

How do you place control on a form?

To place controls on your form, you select them in the Toolbox and then draw, on the form, the rectangle in which the control will be enclosed. Or you can double-click the control's icon to place an instance of the control on the form.

What is user control in Winforms?

A UserControl is a collection of controls placed together to be used in a certain way. For example you can place a GroupBox that contains Textbox's, Checkboxes, etc. This is useful when you have to place the same group of controls on/in multiple forms or tabs.


2 Answers

Call the GetChildIndex and SetChildIndex methods of the parent's Controls collection.

like image 81
SLaks Avatar answered Oct 01 '22 14:10

SLaks


There is no Z-order as there was in VB, but you can use the GetChildIndex and SetChildIndex methods to get and set their indexes manually.

Here there's an example of how to use it. You will probably need to keep a record of each controls index though so you can set it back to it when it's finished with.

Something like this is probably what you're after:

// Get the controls index int zIndex = parentControl.Controls.GetChildIndex(textBox); // Bring it to the front textBox.BringToFront(); // Do something... // Then send it back again parentControl.Controls.SetChildIndex(textBox, zIndex); 
like image 40
Iain Ward Avatar answered Oct 01 '22 12:10

Iain Ward