问题
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!)
回答1:
Call the GetChildIndex and SetChildIndex methods of the parent's Controls
collection.
回答2:
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);
回答3:
When used with the FlowLayoutPanel this will move a control up or down
/// <summary>
/// When used with the FlowLayoutPanel this will move a control up or down
/// </summary>
/// <param name="sender"></param>
/// <param name="UpDown"></param>
private void C_On_Move(object sender, int UpDown)
{
//If UpDown = 1 Move UP, If UpDown = 0 Move DOWN
Control c = (Control)sender;
// Get the controls index
int zIndex = _flowLayoutPanel1.Controls.GetChildIndex(c);
if (UpDown==1 && zIndex > 0)
{
// Move up one
_flowLayoutPanel1.Controls.SetChildIndex(c, zIndex - 1);
}
if (UpDown == 0 && zIndex < _flowLayoutPanel1.Controls.Count-1)
{
// Move down one
_flowLayoutPanel1.Controls.SetChildIndex(c, zIndex + 1);
}
}
来源:https://stackoverflow.com/questions/3213270/how-to-set-z-order-of-a-control-using-winforms