2013-08-21 49 views
-2

我有数字按钮,当按下时在不同的文本框中显示数字。现在我的问题是,我想检查哪些文本框具有焦点,以便按下的数字将被输入到该文本框中。 我的代码:在C#Winforms中设置焦点的文本框值

private void btn_one_Click(object sender, EventArgs e) 
{ 
    if (txt_one.Focused==true) 
    { 
     txt_one.Text += btn_one.Text; 
    } 
    else if (txt_two.Focused==true) 
    { 
     txt_two.Text += btn_one.Text; 
    } 
} 

现在我的问题是,上面的代码不工作什么是错,什么将是解决办法吗?我竟然用这样的

private void btn_one_Click(object sender, EventArgs e) 
{ 
    if (txt_one.Focus()==true) 
    { 
     txt_one.Text += btn_one.Text; 
    } 
    else if (txt_two.Focus()=true) 
    { 
     txt_two.Text += btn_one.Text; 
    } 
} 

在这两个文本在两个文本框中输入了上述情况。任何解决方案

+1

你真的不问问题。有什么不工作? – xdumaine

+0

你的表单和一个实际问题的屏幕截图将帮助 –

+0

显示你的工作..无法获得点。 –

回答

2

这个问题有点棘手(根据我的经验处理Enter, Focus, LostFocus, Leave事件,所有这些事情有时会使你的头部疼痛很多,如果可能的话,你应该避免与他们打交道),当你点击你的Button时, Focused控制你可以知道确切的是ButtonActiveControl是访问它的一个简单方法)。因此,解决方案是我们必须记录重点TextBox的轨迹,将其保存在参考中并在需要时使用。事实上,如果不是你TextBoxes的另一个控制的重点是,我们要变lastFocused重置为空:

TextBox lastFocused; 
//Enter event handler for all your TextBoxes 
private void TextBoxes_Enter(object sender, EventArgs e){ 
    lastFocused = sender as TextBox; 
} 
//Click event handler for your button 
private void btn_one_Click(object sender, EventArgs e){ 
    if(lastFocused != null) lastFocused.Text += btn_one.Text; 
} 
+0

感谢您的答案@ King King,但上述代码无法正常工作。 – ROM

+0

@ROM你知道如何为** all **的文本框注册'Enter'事件处理程序吗? –

+0

对不起@王金我现在工作感谢千位先生。 – ROM