如何确定哪个文本框是关注的并向其添加文本...........?

时间:2012-10-24 06:30:04

标签: c# winforms

我在C#中做一个复杂的计算器。第一个文本框接受真实部分,第二个文本框接受虚构部分。我也希望能够使用鼠标输入值。所以,如果我点击button1,它将会结束" 1"到焦点所在的文本框中的值。我无法确定哪个文本框是关注的。我尝试了一些人发布的东西,比如使用GotFocus作为例子,而且没有用过..

    private Control focusedControl;

    private void TextBox_GotFocus(object sender, EventArgs e)
    {
        focusedControl = (Control)sender;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        if (focusedControl != null)
        {
            focusedControl.Focus();
            SendKeys.Send("1"); 

        }

    }

4 个答案:

答案 0 :(得分:6)

private TextBox focusedControl;

private void TextBox_GotFocus(object sender, EventArgs e)
{
    focusedControl = (TextBox)sender;
}


private void button1_Click(object sender, EventArgs e)
{
    if (focusedControl != null)
    {   

        focusedControl.Text  += "1";
    }

}

您只需使用TextBox_GotFocus作为两个文本框的EventHandler。

答案 1 :(得分:3)

        if ((txtBox as Control).Focused)
        {

        }

答案 2 :(得分:2)

public partial class Form1 : Form 
{ 
    private TextBox focusedTextbox = null; 

    public Form1() 
    { 
        InitializeComponent(); 
        foreach (TextBox tb in this.Controls.OfType<TextBox>()) 
        { 
            tb.Enter += textBox_Enter; 
        } 
    } 

    void textBox_Enter(object sender, EventArgs e) 
    { 
        focusedTextbox = (TextBox)sender; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
        if (focusedTextbox != null) 
        { 
            // put something in textbox 

        } 
    } 
} 

答案 3 :(得分:1)

我在互联网上找到了这个代码,告诉我你的想法:)

    private TextBox findFocused(Control parent)
    {
        foreach (Control ctl in parent.Controls)
        {
            if (ctl.HasChildren == true)
                return findFocused(ctl);
            else if (ctl is TextBox && ctl.Focused)
                return ctl as TextBox;
        }

        return null;
    }
// usage: if starting with the form  
TextBox txt = findFocused(this);
祝你好运!