日期:2014-05-18  浏览次数:20850 次

winform 获得焦点 在线等 急
界面有 a,b,c,d 四个文本框 按abcd先后顺序来输入值 ,每个控件都写了 enter和 leave事件,
比如现在焦点在a文本框 但是没有输入值,直接按了tab键 焦点到了b文本框
 我在b文本框的enter事件里 判断a文本框是否是string.Empty,如果是就弹出提示框 “a文本框没输入值”
 然后把焦点移到a文本框 但是 他一直弹出提示死循环了
b的leave事件里写的是 判断如果a为string.empty 则把焦点移到a文本框 否则移到文本框 
c文本框写的事件跟b文本框差不多 

C# code

//a 文本框
private void txtTSPName_Enter(object sender, EventArgs e)
        {
            if (txtTSPName.Text.Trim() != string.Empty && txtTrayCode.Text.Trim() != string.Empty )
            {
                MessageBox.Show("不能更改承运商编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (txtGoodCode.Text == string.Empty) txtGoodCode.Focus();
                if(txtWeight.Text==string.Empty)txtWeight.Focus();
                
            }
        }

 private void txtTSPName_Leave(object sender, EventArgs e)
        {
                txtTrayCode.Focus();
        }

//b文本框
 private void txtTrayCode_Enter(object sender, EventArgs e)
        {
           
            if (txtTSPName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请先输入承运商编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTSPName.Focus();
            }
            else if (txtTSPName.Text.Trim() != string.Empty && txtTrayCode.Text.Trim() != string.Empty && txtGoodCode.Text.Trim() != string.Empty)
            {
                MessageBox.Show("不能更改托盘号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (txtGoodCode.Text == string.Empty) txtGoodCode.Focus();
                if (txtWeight.Text == string.Empty) txtWeight.Focus();//txtWeight是d文本框
            }
        }



 private void txtTrayCode_Leave(object sender, EventArgs e)
        {
            if (txtTSPName.Text == string.Empty)
            {
                txtTSPName.Focus();
            }
            else
            {
                txtGoodCode.Focus();
            }
        }

//c 文本框
private void txtGoodCode_Enter(object sender, EventArgs e)
        {
            if (txtTSPName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请先输入承运商编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTSPName.Focus();
            }
            else
                if (txtTrayCode.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("请先扫描托盘号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtTrayCode.Focus();
                }
        }

  private void txtGoodCode_Leave(object sender, EventArgs e)
        {
            txtWeight.Focus();
        }



------解决方案--------------------
为什么不在A文本框Leave的时候判断一下。而在B文本框Enter的时候判断A的?
------解决方案--------------------
当然了,你显示提示框,就会触发leave事件,leave事件有focus,又会触发enter事件,必循环无止,你应该在每个控件的回车事件中,判断是否数据满足,如果不满足,就不允许离开,不要再Leave事件中处理