在C#中获取当前关注的文本框 [英] Get the currently focused textbox in C#

查看:73
本文介绍了在C#中获取当前关注的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本框和一个按钮.当我按下按钮时,我想知道我当前的插入符号在哪里(两个方框中的一个).我需要此信息才能知道在何处插入特定文本.我尝试了 textbox1.Focused ; textbox1.enabled ,但均无效.我应该如何实施呢?谢谢

I have two textboxes, and a button. When I press the button, I want to know where my current caret 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.

尝试类似的方法

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

这篇关于在C#中获取当前关注的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆