开发者

Get the currently focused textbox in C#

I have two textboxes, and a button. When I press the button, I want to know where my current caret开发者_JAVA技巧 is (either of the two boxes). I need this to know where to insert a certain text. I tried textbox1.Focused; textbox1.enabled but neither worked. How should I implement this? Thanks


Keep in mind that when you click the button, your textboxes will no longer have focus. You'll want a method of keeping track of what was in focus before the button's click event.

Try something like this

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
            focusedTextbox.Text = DateTime.Now.ToString();
        }
    }
}


There's a very simple way to do this. Your requirement is simple since you only have two textboxes.

You can assign a class-wide string variable that holds when textbox1_GotFocus() is invoked as well as textbox2_GotFocus(). So if that textbox GotFocus() is called you assign a value. Then put a condition for the class-wide string variable in the button that if the class-wide variable has a value of thats kind, that textbox is populated whatever you want to put in the textbox.

It worked for me so I believe it should work on you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜