簡體   English   中英

如何確定要聚焦的文本框並向其中添加文本…?

[英]how to determine which textbox is focused and add text to it…?

我在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"); 

        }

    }
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。

        if ((txtBox as Control).Focused)
        {

        }
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 

        } 
    } 
} 

我在互聯網上找到了此代碼,請告訴我您的想法:)

    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);

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM