运行时选择界面上控件的方法
看到很多入门人员(C#我也是入门者)找如何在运行时选择界面上控件,因此写了这段代码,希望有所帮助.
用左键确定选择,选择后置控件的背景颜色(如能像微软一样显示一个句柄就更好,觉得不难)
static Control oldCtr;
static Color oldColor;
private void timer1_Tick(object sender, EventArgs e)
{
//左键确认选择
if (Control.MouseButtons == MouseButtons.Left)
{
Control ctr = FindControl(this);
if (ctr != null)
{
//复原先前控件属性
if (oldCtr != null)
{
oldCtr.BackColor = oldColor;
}
//保存选择并置选择状态
oldCtr = ctr;
oldColor = ctr.BackColor;
ctr.BackColor = Color.Red;
}
}
}
private Control FindControl(Control pControl)
{
Control ctr ;
ctr = pControl.GetChildAtPoint(pControl.PointToClient(Control.MousePosition));
//直接在容器中
if (ctr != null)
{
//无子控件
if (ctr.Controls.Count == 0)
{
return (ctr);
}
else
{
Control ctr2 = FindControl(ctr);
if (ctr2 != null)
{
//子控件处于选择状态则返回子控件
return (ctr2);
}
else
{
//子控件不处于选择状态则返回容器控件
return (ctr);
}
}
}
return (null);
}