2

我正在用 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

4 回答 4

6
        if ((txtBox as Control).Focused)
        {

        }
于 2014-04-22T22:04:10.213 回答
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。

于 2012-10-24T06:37:04.927 回答
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 

        } 
    } 
} 
于 2012-10-24T06:41:30.670 回答
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);

祝你好运!

于 2012-10-24T06:40:49.293 回答